Merge pull request 'Generate openldap types through trailing-dot chains and File.join arrays' (#17) from benvin/gentypes-openldap into main

Reviewed-on: #17
This commit was merged in pull request #17.
This commit is contained in:
2026-11-09 23:01:15 +11:00
29 changed files with 2773 additions and 5 deletions
+16
View File
@@ -317,3 +317,19 @@ func TestOnigCheck(t *testing.T) {
}
}
}
// Each case is Ruby 3.3's File.join of parts.
func TestFileJoin(t *testing.T) {
for _, c := range []struct {
parts []string
want string
}{
{[]string{"a", ""}, "a/"}, {[]string{"", "a"}, "/a"}, {[]string{"/", "b"}, "/b"}, {[]string{"a//", "b"}, "a//b"},
{[]string{"a/", "/b"}, "a/b"}, {[]string{"//", "//b"}, "//b"}, {[]string{"a", "/"}, "a/"}, {[]string{"/", "/"}, "/"},
{[]string{"", "/"}, "/"}, {[]string{"a", "", " b"}, "a/ b"}, {[]string{"x", "", ""}, "x/"}, {nil, ""},
} {
if got := fileJoin(c.parts); got != c.want {
t.Errorf("fileJoin(%q) = %q, want %q", c.parts, got, c.want)
}
}
}
+5
View File
@@ -54,6 +54,7 @@ func TestFidelityPuppetWritesNothing(t *testing.T) {
"provider sets @doc": provider("Puppet::Type.type(:t).provide(:x) do\n @doc = 1\nend\n"),
"provider sets $stdout": provider("Puppet::Type.type(:t).provide(:x) do\n $stdout = 1\nend\n"),
"provider aliases undefined method": provider("Puppet::Type.type(:t).provide(:x) do\n alias_method :a, :nope\nend\n"),
"File.join of a symbol array": provider("require File.join(File.dirname(__FILE__), %i[x])\nPuppet::Type.type(:t).provide(:x) do\nend\n"),
"provider superclass mismatch": provider("class QHelper < StandardError\nend\nclass QHelper < Puppet::Error\nend\nPuppet::Type.type(:t).provide(:x) do\nend\n"),
"library redefines a Puppet::Type method": {"m/lib/puppet_x/m/patch.rb": "class Puppet::Type\n def self.newparam(*)\n raise 'patched'\n end\nend\n",
"m/lib/puppet/type/t.rb": "require 'puppet_x/m/patch'\n" + classic},
@@ -149,6 +150,10 @@ func TestFidelityProvidersThatLoad(t *testing.T) {
"parsed file records": provider("require 'puppet/provider/parsedfile'\nPuppet::Type.type(:t).provide(:x, parent: Puppet::Provider::ParsedFile, default_target: '/tmp/x') do\n" +
" text_line :blank, match: %r{^\\s*$}\n record_line :x, fields: ['name'], optional: ['name'], to_line: proc { |h| h[:name] }\n" +
" record_line :y, fields: %w[name], block_eval: :instance do\n def to_line(h)\n h[:name]\n end\n end\nend\n"),
"trailing-dot chain and File.join arrays": {"m/lib/puppet/type/t.rb": classic,
"m/lib/puppet/provider/h.rb": "class Puppet::Provider::H < Puppet::Provider\n initvars\n commands h: 'h'\nend\n",
"m/lib/puppet/provider/t/x.rb": "require File.expand_path(File.join(File.dirname(__FILE__), %w[..], ['x', [], '/../h']))\nPuppet::Type.\n # c\n type(:t).\n\n" +
" provide(:x, parent: Puppet::Provider::H) do\n defaultfor osfamily: %i[a b]\nend\n"},
"helper required by path": {"m/lib/puppet/type/t.rb": classic,
"m/lib/puppet/provider/h.rb": "require 'json'\nclass Puppet::Provider::H < Puppet::Provider\n initvars\n commands a: 'a'\nend\n",
"m/lib/puppet/provider/t/x.rb": "require File.expand_path(File.join(File.dirname(__FILE__), '..', 'h'))\nPuppet::Type.type(:t).provide(:x, parent: Puppet::Provider::H) do\nend\n"},
+1 -1
View File
@@ -18,7 +18,7 @@ import (
const OutDir = ".resource_types"
// Version changes whenever generated output can change, so deploys rebuild typed environments.
const Version = "10"
const Version = "11"
var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
+15
View File
@@ -775,3 +775,18 @@ func TestGeneratePanicFailsTheEnv(t *testing.T) {
t.Fatalf("a panic must be a hard error, got %v", err)
}
}
// Ruby continues a line that ends in a method-call dot, across blank and comment lines.
func TestLexTrailingDot(t *testing.T) {
toks, err := lex("a.\n # c\n\n b&.\n c\nd\n")
if err != nil {
t.Fatal(err)
}
var got []string
for _, tk := range toks {
got = append(got, tk.text)
}
if s := strings.Join(got, " "); s != "a . b &. c d " {
t.Fatalf("tokens %q", s)
}
}
+3 -1
View File
@@ -148,7 +148,9 @@ func (l *lexer) run() error {
continue
case c == '\n':
l.pos++
l.emit(token{kind: tNL})
if t := l.last(); t == nil || t.kind != tOp || t.text != "." && t.text != "&." {
l.emit(token{kind: tNL})
}
l.line++
if err := l.readHeredocs(); err != nil {
return err
+49 -3
View File
@@ -914,7 +914,7 @@ func (p *parser) pathExpr(depth int) (string, error) {
var args []string
for !p.op(")") {
p.skipNL()
a, err := p.pathExpr(depth + 1)
a, err := p.joinArg(fn, depth+1)
if err != nil {
return "", err
}
@@ -930,8 +930,8 @@ func (p *parser) pathExpr(depth int) (string, error) {
return "", err
}
switch {
case fn == "join" && len(args) > 0:
return strings.Join(args, "/"), nil
case fn == "join":
return fileJoin(args), nil
case fn == "dirname" && len(args) == 1:
return path.Dir(args[0]), nil
case fn == "expand_path" && (len(args) == 1 || len(args) == 2):
@@ -948,6 +948,52 @@ func (p *parser) pathExpr(depth int) (string, error) {
return "", fmt.Errorf("unsupported require path %s", describe(t))
}
// joinArg reads one File.<fn> argument; File.join takes %w and literal arrays, which it joins recursively.
func (p *parser) joinArg(fn string, depth int) (string, error) {
t := p.cur()
switch {
case fn == "join" && t.kind == tWords && t.flags == "w" && !slices.ContainsFunc(t.words, func(w string) bool { return strings.Contains(w, "\\") }):
p.take()
return fileJoin(t.words), nil
case fn == "join" && t.kind == tOp && t.text == "[":
p.take()
var elems []string
for p.skipNL(); !p.op("]"); p.skipNL() {
e, err := p.joinArg(fn, depth+1)
if err != nil {
return "", err
}
elems = append(elems, e)
if p.skipNL(); !p.op(",") {
break
}
p.take()
}
return fileJoin(elems), p.expect("]")
}
return p.pathExpr(depth)
}
// fileJoin is Ruby's File.join: one separator between parts, keeping a part's leading one and the doubled ones within.
func fileJoin(parts []string) string {
var b strings.Builder
for i, s := range parts {
if i > 0 {
cur := b.String()
trimmed := strings.TrimRight(cur, "/")
switch {
case strings.HasPrefix(s, "/"):
b.Reset()
b.WriteString(trimmed)
case len(trimmed) == len(cur):
b.WriteByte('/')
}
}
b.WriteString(s)
}
return b.String()
}
// provDecl is a provide call: its name, its parent by provider name or class, and its class body.
type provDecl struct {
name, parent, sup string
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,236 @@
# frozen_string_literal: true
require 'tempfile'
class Puppet::Provider::Openldap < Puppet::Provider
initvars # without this, commands won't work
commands original_slapcat: 'slapcat',
original_ldapmodify: 'ldapmodify',
original_ldapadd: 'ldapadd'
def self.slapcat(filter, dn = '', base = 'cn=config')
arguments = [
'-b', base,
'-o', 'ldif-wrap=no',
'-H', "ldap:///#{dn}???#{filter}"
]
original_slapcat(*arguments)
end
def slapcat(*args)
self.class.slapcat(*args)
end
def self.ldapadd(path)
original_ldapadd('-cQY', 'EXTERNAL', '-H', 'ldapi:///', '-f', path)
end
def ldapadd(*args)
self.class.ldapadd(*args)
end
# Unwrap LDIF and return each attribute beginning with "olc" also removing
# that occurance of "olc" at the beginning.
def self.get_lines(items)
items.strip.
gsub("\n ", '').
split("\n").
grep(%r{^olc}).
map { |entry| entry.gsub(%r{^olc}, '') }
end
def get_lines(*args)
self.class.get_lines(*args)
end
# Unwrap LDIF and return each entry as array of lines.
#
# Example LDIF:
# dn: cn=config
# ...
#
# dn: cn=schema,cn=config
# ...
#
# Results in:
#
# [['dn: cn=config', '...'],
# ['dn: cn=schema,cn=config', '...']]
#
def self.get_entries(items)
items.strip.
split("\n\n").
map do |paragraph|
paragraph.
gsub("\n ", '').
split("\n")
end
end
def get_entries(*args)
self.class.get_entries(*args)
end
def self.last_of_split(line, by = ' ')
line.split(by, 2).last
end
def last_of_split(*args)
self.class.last_of_split(*args)
end
def self.ldapmodify(path)
original_ldapmodify('-Y', 'EXTERNAL', '-H', 'ldapi:///', '-f', path)
end
def ldapmodify(*args)
self.class.ldapmodify(*args)
end
def self.temp_ldif(name = 'openldap_ldif')
Tempfile.new(name)
end
def temp_ldif(*args)
self.class.temp_ldif(*args)
end
def delimit
"-\n"
end
def cn_config
dn('cn=config')
end
def dn(dn)
"dn: #{dn}\n"
end
def changetype(t)
"changetype: #{t}\n"
end
def add(key)
"add: olc#{key}\n"
end
def del(key)
"delete: olc#{key}\n"
end
def replace_key(key)
"replace: olc#{key}\n"
end
def key_value(key, value)
"olc#{key}: #{value}\n"
end
def add_or_replace_key(key, force_replace = :false)
# This list of possible attributes of cn=config has been extracted from a
# running slapd with the following command:
# ldapsearch -s base -b cn=Subschema attributeTypes -o ldif-wrap=no | \
# grep SINGLE-VALUE | grep "NAME 'olc" | \
# sed -e "s|.*NAME '||g" \
# -e "s|' SYNTAX.*||g" \
# -e "s|' EQUALITY.*||g" \
# -e "s|' DESC.*||g"
single_value_attributes = %w[
ConfigFile
ConfigDir
AddContentAcl
ArgsFile
AuthzPolicy
Backend
Concurrency
ConnMaxPending
ConnMaxPendingAuth
Database
DefaultSearchBase
GentleHUP
Hidden
IdleTimeout
IndexSubstrIfMinLen
IndexSubstrIfMaxLen
IndexSubstrAnyLen
IndexSubstrAnyStep
IndexIntLen
LastMod
ListenerThreads
LocalSSF
LogFile
MaxDerefDepth
MirrorMode
ModulePath
Monitoring
MultiProvider
Overlay
PasswordCryptSaltFormat
PidFile
PluginLogFile
ReadOnly
Referral
ReplicaArgsFile
ReplicaPidFile
ReplicationInterval
ReplogFile
ReverseLookup
RootDN
RootPW
SaslAuxprops
SaslHost
SaslRealm
SaslSecProps
SchemaDN
SizeLimit
SockbufMaxIncoming
SockbufMaxIncomingAuth
Subordinate
SyncUseSubentry
Threads
TLSCACertificateFile
TLSCACertificatePath
TLSCertificateFile
TLSCertificateKeyFile
TLSCipherSuite
TLSCRLCheck
TLSCRLFile
TLSRandFile
TLSVerifyClient
TLSDHParamFile
TLSProtocolMin
ToolThreads
UpdateDN
WriteTimeout
DbDirectory
DbCheckpoint
DbNoSync
DbMaxReaders
DbMaxSize
DbMode
DbSearchStack
PPolicyDefault
PPolicyHashCleartext
PPolicyForwardUpdates
PPolicyUseLockout
MemberOfDN
MemberOfDangling
MemberOfRefInt
MemberOfGroupOC
MemberOfMemberAD
MemberOfMemberOfAD
MemberOfDanglingError
SpCheckpoint
SpSessionlog
SpNoPresent
SpReloadHint
]
use_replace = single_value_attributes.include?(key.to_s) || force_replace == :true
use_replace ? replace_key(key) : add(key)
end
end
@@ -0,0 +1,206 @@
# frozen_string_literal: true
require File.expand_path(File.join(File.dirname(__FILE__), %w[.. openldap]))
require 'tempfile'
# rubocop:disable Naming/VariableName
# rubocop:disable Naming/MethodName
# rubocop:disable Lint/AssignmentInCondition
Puppet::Type.
type(:openldap_access).
provide(:olc, parent: Puppet::Provider::Openldap) do
# TODO: Use ruby bindings (can't find one that support IPC)
defaultfor osfamily: %i[debian freebsd redhat suse]
mk_resource_methods
def self.instances
# TODO: restict to bdb, hdb and globals
i = []
slapcat('(olcAccess=*)').split("\n\n").map do |paragraph|
access = nil
suffix = nil
position = nil
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcDatabase: }
suffix = "cn=#{line.split[1].gsub(%r{\{-?\d+\}}, '')}"
when %r{^olcSuffix: }
suffix = line.split[1]
when %r{^olcAccess: }
begin
position, what, bys = line.match(%r{^olcAccess:\s+\{(\d+)\}to\s+(\S+(?:\s+filter=\S+)?(?:\s+attrs=\S+)?(?:\s+val=\S+)?)(\s+by\s+.*)+$}).captures
rescue StandardError
raise Puppet::Error, "Failed to parse olcAccess for suffix '#{suffix}': #{line}"
end
access = []
bys.split(%r{(?= by .+)}).each do |b|
access << b.lstrip
end
i << new(
name: "#{position} on #{suffix}",
ensure: :present,
position: position,
what: what,
access: access,
suffix: suffix
)
end
end
end
i
end
def self.prefetch(resources)
accesses = instances
resources.each_key do |name|
next unless provider = accesses.find do |access|
if resources[name][:position]
access.suffix == resources[name][:suffix] &&
access.position == resources[name][:position].to_s
else
access.suffix == resources[name][:suffix] &&
access.access.flatten == resources[name][:access].flatten &&
access.what == resources[name][:what]
end
end
resources[name].provider = provider
end
end
def self.getDn(suffix)
case suffix
when 'cn=frontend'
'olcDatabase={-1}frontend,cn=config'
when 'cn=config'
'olcDatabase={0}config,cn=config'
when 'cn=monitor'
slapcat('(olcDatabase=monitor)').split("\n").map do |line|
return line.split[1] if line =~ %r{^dn: }
end
else
slapcat("(olcSuffix=#{suffix})").split("\n").map do |line|
return line.split[1] if line =~ %r{^dn: }
end
end
end
def getDn(*args)
self.class.getDn(*args)
end
def exists?
@property_hash[:ensure] == :present
end
def create
t = Tempfile.new('openldap_access')
t << "dn: #{getDn(resource[:suffix])}\n"
t << "add: olcAccess\n"
t << if resource[:position]
"olcAccess: {#{resource[:position]}}to #{resource[:what]}\n"
else
"olcAccess: to #{resource[:what]}\n"
end
resource[:access].flatten.each do |a|
t << " #{a}\n"
end
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
def destroy
t = Tempfile.new('openldap_access')
t << "dn: #{getDn(@property_hash[:suffix])}\n"
t << "changetype: modify\n"
t << "delete: olcAccess\n"
t << "olcAccess: {#{@property_hash[:position]}}\n"
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
def initialize(value = {})
super(value)
@property_flush = {}
end
def access=(value)
@property_flush[:access] = value.flatten
end
def self.getCountOfOlcAccess(suffix)
countOfElement = 0
slapcat('(olcAccess=*)', getDn(suffix).to_s).split("\n\n").map do |paragraph|
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcAccess: }
countOfElement += 1
end
end
end
countOfElement
end
def getCurrentOlcAccess(suffix)
i = []
slapcat('(olcAccess=*)', getDn(suffix).to_s).split("\n\n").map do |paragraph|
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcAccess: }
position, content = line.match(%r{^olcAccess:\s+\{(\d+)\}(.*)$}).captures
i << {
position: position,
content: content,
}
end
end
end
i
end
def flush
unless @property_flush.empty?
current_olcAccess = getCurrentOlcAccess(resource[:suffix])
t = Tempfile.new('openldap_access')
t << "dn: #{getDn(resource[:suffix])}\n"
t << "changetype: modify\n"
t << "replace: olcAccess\n"
position = resource[:position] || @property_hash[:position]
current_olcAccess.each do |olc_access|
if olc_access[:position].to_i == position.to_i
t << "olcAccess: {#{position}}to #{resource[:what]}\n"
resource[:access].flatten.each do |a|
t << " #{a}\n"
end
else
t << "olcAccess: {#{olc_access[:position]}}#{olc_access[:content]}\n"
end
end
self.class.getCountOfOlcAccess(resource[:suffix])
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
@property_hash = resource.to_hash
end
end
# rubocop:enable Naming/VariableName
# rubocop:enable Naming/MethodName
# rubocop:enable Lint/AssignmentInCondition
@@ -0,0 +1,435 @@
# frozen_string_literal: true
require File.expand_path(File.join(File.dirname(__FILE__), %w[.. openldap]))
require 'base64'
Puppet::Type.
type(:openldap_database).
provide(:olc, parent: Puppet::Provider::Openldap) do
# TODO: Use ruby bindings (can't find one that support IPC)
defaultfor osfamily: %i[debian freebsd redhat suse]
mk_resource_methods
def self.instances
databases = slapcat('(|(olcDatabase=monitor)(olcDatabase={0}config)(&(objectClass=olcDatabaseConfig)(|(objectClass=olcBdbConfig)(objectClass=olcHdbConfig)(objectClass=olcMdbConfig)(objectClass=olcMonitorConfig)(objectClass=olcRelayConfig)(objectClass=olcLDAPConfig))))')
databases.split("\n\n").map do |paragraph|
suffix = nil
relay = nil
index = nil
backend = nil
directory = nil
rootdn = nil
rootpw = nil
readonly = nil
sizelimit = nil
dbmaxsize = nil
timelimit = nil
updateref = nil
dboptions = {}
mirrormode = nil
multiprovider = nil
syncusesubentry = nil
syncrepl = nil
limits = []
security = {}
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcDatabase: }
index, backend = line.match(%r{^olcDatabase: \{(\d+)\}(bdb|hdb|mdb|monitor|config|relay|ldap)$}).captures
when %r{^olcDbDirectory: }
directory = line.split[1]
when %r{^olcRootDN: }
rootdn = line.split[1]
when %r{^olcRootPW:: }
rootpw = Base64.decode64(line.split[1])
when %r{^olcSuffix: }
suffix = line.split[1]
when %r{^olcRelay: }
relay = line.split[1]
when %r{^olcReadOnly: }i
readonly = line.split[1]
when %r{^olcSizeLimit: }i
sizelimit = line.split[1]
when %r{^olcDbMaxSize: }i
dbmaxsize = line.split[1]
when %r{^olcTimeLimit: }i
timelimit = line.split[1]
when %r{^olcUpdateref: }i
updateref = line.split[1]
when %r{^olcDb\S+: }i
optname, optvalue = line.split(': ', 2)
optname.downcase!
case optname
when 'olcdbconfig'
dboptions['dbconfig'] = [] unless dboptions['dbconfig']
optvalue = optvalue.match(%r{^\{\d+\}(.+)$}).captures[0] if optvalue =~ %r{^\{\d+\}.+$}
dboptions['dbconfig'].push(optvalue)
when 'olcdbnosync'
dboptions['dbnosync'] = optvalue
when 'olcdbpasesize'
dboptions['dbpagesize'] = optvalue
else
ldifoptname = optname.match(%r{^olcDb(\S+)$}i).captures[0]
if dboptions[ldifoptname] && !dboptions[ldifoptname].is_a?(Array)
dboptions[ldifoptname] = [dboptions[ldifoptname]]
dboptions[ldifoptname].push(optvalue)
elsif dboptions[ldifoptname]
dboptions[ldifoptname].push(optvalue)
else
dboptions[optname.match(%r{^olcDb(\S+)$}i).captures[0]] = optvalue
end
end
when %r{^olcMirrorMode: }
mirrormode = line.split[1] == 'TRUE' ? :true : :false
when %r{^olcMultiProvider: }
multiprovider = line.split[1] == 'TRUE' ? :true : :false
when %r{^olcSyncUseSubentry: }
syncusesubentry = line.split(' ', 2)[1]
when %r{^olcSyncrepl: }
syncrepl ||= []
optvalue = line.split(' ', 2)[1]
syncrepl.push(optvalue.match(%r{^(\{\d+\})?(.+)$}).captures[1])
when %r{^olcLimits: }
limit = line.match(%r{^olcLimits:\s+(\{\d+\})?(.+)$}).captures[1]
limits << limit
when %r{^olcSecurity: }
line.split(': ')[1].split.each do |variable|
values = variable.split('=')
security[values[0]] = values[1].to_i
end
end
end
suffix = "cn=#{backend}" if backend.match(%r{monitor}i) && !suffix
suffix = "cn=#{backend}" if backend.match(%r{config}i) && !suffix
suffix = "cn=#{backend}" if backend.match(%r{ldap}i) && !suffix
new(
ensure: :present,
name: suffix,
suffix: suffix,
relay: relay,
index: index.to_i,
backend: backend,
directory: directory,
rootdn: rootdn,
rootpw: rootpw,
readonly: readonly,
sizelimit: sizelimit,
timelimit: timelimit,
dbmaxsize: dbmaxsize,
updateref: updateref,
dboptions: dboptions,
mirrormode: mirrormode,
multiprovider: multiprovider,
syncusesubentry: syncusesubentry,
syncrepl: syncrepl,
limits: limits,
security: security
)
end
end
def self.prefetch(resources)
databases = instances
resources.each_key do |name|
if (provider = databases.find { |database| database.name == name })
resources[name].provider = provider
end
end
end
def exists?
@property_hash[:ensure] == :present
end
def fetch_index
slapcat("(&(objectClass=olc#{@property_hash[:backend].to_s.capitalize}Config)(olcSuffix=#{@property_hash[:suffix]}))").split("\n").map do |line|
@property_hash[:index] = line.match(%r{^olcDatabase: \{(\d+)\}#{@property_hash[:backend]}$}).captures[0].to_i if line =~ %r{^olcDatabase: }
end
end
def destroy
default_confdir = {
'Debian' => '/etc/ldap/slapd.d',
'RedHat' => '/etc/openldap/slapd.d',
'FreeBSD' => '/usr/local/etc/openldap/slapd.d',
}[Facter.value(:osfamily)]
backend = @property_hash[:backend]
fetch_index
`service slapd stop`
File.delete("#{default_confdir}/cn=config/olcDatabase={#{@property_hash[:index]}}#{backend}.ldif")
slapcat("(objectClass=olc#{backend.to_s.capitalize}Config)").
split("\n").
grep(%r{^dn: }).
select { |dn| dn.match(%r{^dn: olcDatabase={(\d+)}#{backend},cn=config$}).captures[0].to_i > @property_hash[:index] }.
each do |dn|
index = dn[%r{\d+}].to_i
old_filename = "#{default_confdir}/cn=config/olcDatabase={#{index}}#{backend}.ldif"
new_filename = "#{default_confdir}/cn=config/olcDatabase={#{index - 1}}#{backend}.ldif"
File.rename(old_filename, new_filename)
text = File.read(new_filename)
replace = text.gsub!("{#{index}}#{backend}", "{#{index - 1}}#{backend}")
File.open(new_filename, 'w') { |file| file.puts replace }
end
`service slapd start`
@property_hash.clear
end
def initdb
t = Tempfile.new('openldap_database')
t << "dn: #{resource[:suffix]}\n"
t << "changetype: add\n"
t << "objectClass: top\n"
t << "objectClass: dcObject\n" if resource[:suffix].start_with?('dc=')
t << "objectClass: organization\n"
t << "dc: #{resource[:suffix].split(%r{,?dc=}).delete_if(&:empty?)[0]}\n" if resource[:suffix].start_with?('dc=')
t << "o: #{resource[:organization]}\n" if resource[:organization]
if resource[:rootdn]
t << "\n"
t << "dn: #{resource[:rootdn]}\n"
t << "objectClass: simpleSecurityObject\n" if resource[:rootpw]
t << "objectClass: organizationalRole\n"
t << "cn: #{resource[:rootdn].split(%r{,|=})[1]}\n"
t << "description: LDAP administrator\n"
t << "userPassword: #{resource[:rootpw]}\n" if resource[:rootpw]
end
t.close
Puppet.debug(File.read(t.path))
begin
ldapadd(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
t.delete
end
def create
if resource[:rootpw] && resource[:rootpw] !~ %r{^\{(CRYPT|MD5|SMD5|SSHA|SHA(256|384|512)?)\}.+}
require 'securerandom'
salt = SecureRandom.random_bytes(4)
@resource[:rootpw] = "{SSHA}#{Base64.encode64("#{Digest::SHA1.digest("#{resource[:rootpw]}#{salt}")}#{salt}").chomp}"
end
t = Tempfile.new('openldap_database')
t << "dn: olcDatabase=#{resource[:backend]},cn=config\n"
t << "changetype: add\n"
t << "objectClass: olcDatabaseConfig\n"
t << "objectClass: olc#{resource[:backend].to_s.capitalize}Config\n"
t << "olcDatabase: #{resource[:backend]}\n"
case resource[:backend].to_s
when 'relay'
t << "olcRelay: #{resource[:relay]}\n" unless resource[:relay].empty?
t << "olcSuffix: #{resource[:suffix]}\n" if resource[:suffix]
when 'monitor'
# WRITE HERE FOR MONITOR ONLY
when 'ldap'
# WRITE HERE FOR LDAP ONLY
t << "olcSuffix: #{resource[:suffix]}\n" if resource[:suffix]
else
t << "olcDbDirectory: #{resource[:directory]}\n" if resource[:directory]
t << "olcSuffix: #{resource[:suffix]}\n" if resource[:suffix]
t << "olcDbIndex: objectClass eq\n" if !resource[:dboptions] || !resource[:dboptions]['index']
end
t << "olcRootDN: #{resource[:rootdn]}\n" if resource[:rootdn]
t << "olcRootPW: #{resource[:rootpw]}\n" if resource[:rootpw]
t << "olcReadOnly: #{resource[:readonly] == :true ? 'TRUE' : 'FALSE'}\n" if resource[:readonly]
t << "olcSizeLimit: #{resource[:sizelimit]}\n" if resource[:sizelimit]
t << "olcDbMaxSize: #{resource[:dbmaxsize]}\n" if resource[:dbmaxsize]
t << "olcTimeLimit: #{resource[:timelimit]}\n" if resource[:timelimit]
t << "olcUpdateref: #{resource[:updateref]}\n" if resource[:updateref]
resource[:dboptions]&.each do |k, v|
t << case k
when 'dbnosync'
"olcDbNosync: #{v}\n"
when 'dbpagesize'
"olcDbPagesize: #{v}\n"
when 'dbconfig'
v.map { |x| "olcDbConfig: #{x}\n" }.join
else
if v.is_a?(Array)
v.map { |x| "olcDb#{k}: #{x}\n" }.join
else
"olcDb#{k}: #{v}\n"
end
end
end
t << (resource[:syncrepl].map { |x| "olcSyncrepl: #{x}\n" }.join) if resource[:syncrepl]
t << "olcMirrorMode: #{resource[:mirrormode] == :true ? 'TRUE' : 'FALSE'}\n" if resource[:mirrormode]
t << "olcMultiProvider: #{resource[:multiprovider] == :true ? 'TRUE' : 'FALSE'}\n" if resource[:multiprovider]
t << "olcSyncUseSubentry: #{resource[:syncusesubentry]}\n" if resource[:syncusesubentry]
t << "#{resource[:limits].map { |x| "olcLimits: #{x}" }.join("\n")}\n" if resource[:limits] && !resource[:limits].empty?
t << "#{resource[:security].map { |k, v| "olcSecurity: #{k}=#{v}" }.join("\n")}\n" if resource[:security] && !resource[:security].empty?
t << "olcAccess: to * by dn.exact=gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth manage by * break\n"
admin = resource[:rootdn] || "cn=admin,#{resource[:suffix]}"
t << "olcAccess: to attrs=userPassword\n"
t << " by self write\n"
t << " by anonymous auth\n"
t << " by dn=\"#{admin}\" write\n"
t << " by * none\n"
t << "olcAccess: to dn.base=\"\" by * read\n"
t << "olcAccess: to *\n"
t << " by self write\n"
t << " by dn=\"#{admin}\" write\n"
t << " by * read\n"
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
t.delete
initdb if resource[:initdb] == :true
@property_hash[:ensure] = :present
slapcat("(&(objectClass=olc#{resource[:backend].to_s.capitalize}Config)(olcSuffix=#{resource[:suffix]}))").
split("\n").map do |line|
@property_hash[:index] = line.match(%r{^olcDatabase: \{(\d+)\}#{resource[:backend]}$}).captures[0] if line =~ %r{^olcDatabase: }
end
end
def initialize(value = {})
super(value)
@property_flush = {}
end
def directory=(value)
@property_flush[:directory] = value
end
def rootdn=(value)
@property_flush[:rootdn] = value
end
def rootpw=(value)
@property_flush[:rootpw] = value
end
def suffix=(value)
@property_flush[:suffix] = value
end
def relay=(value)
@property_flush[:relay] = value
end
def readonly=(value)
@property_flush[:readonly] = value
end
def sizelimit=(value)
@property_flush[:sizelimit] = value
end
def timelimit=(value)
@property_flush[:timelimit] = value
end
def dbmaxsize=(value)
@property_flush[:dbmaxsize] = value
end
def updateref=(value)
@property_flush[:updateref] = value
end
def dboptions=(value)
@property_flush[:dboptions] = value
end
def mirrormode=(value)
@property_flush[:mirrormode] = value
end
def multiprovider=(value)
@property_flush[:multiprovider] = value
end
def syncusesubentry=(value)
@property_flush[:syncusesubentry] = value
end
def syncrepl=(value)
@property_flush[:syncrepl] = value
end
def limits=(value)
@property_flush[:limits] = value
end
def security=(value)
@property_flush[:security] = value
end
def flush
unless @property_flush.empty?
t = Tempfile.new('openldap_database')
t << "dn: olcDatabase={#{@property_hash[:index]}}#{resource[:backend]},cn=config\n"
t << "changetype: modify\n"
t << "replace: olcDbDirectory\nolcDbDirectory: #{resource[:directory]}\n-\n" if @property_flush[:directory]
t << "replace: olcRootDN\nolcRootDN: #{resource[:rootdn]}\n-\n" if @property_flush[:rootdn]
t << "replace: olcRootPW\nolcRootPW: #{resource[:rootpw]}\n-\n" if @property_flush[:rootpw]
t << "replace: olcSuffix\nolcSuffix: #{resource[:suffix]}\n-\n" if @property_flush[:suffix]
t << "replace: olcRelay\nolcRelay: #{resource[:relay]}\n-\n" if @property_flush[:relay]
t << "replace: olcReadOnly\nolcReadOnly: #{resource[:readonly] == :true ? 'TRUE' : 'FALSE'}\n-\n" if @property_flush[:readonly]
t << "replace: olcSizeLimit\nolcSizeLimit: #{resource[:sizelimit]}\n-\n" if @property_flush[:sizelimit]
t << "replace: olcTimeLimit\nolcTimeLimit: #{resource[:timelimit]}\n-\n" if @property_flush[:timelimit]
t << "replace: olcDbMaxSize\nolcDbMaxSize: #{resource[:dbmaxsize]}\n-\n" if @property_flush[:dbmaxsize]
if @property_flush[:dboptions]
# rubocop:disable Metrics/BlockNesting
if resource[:synctype].to_s == 'inclusive' && !@property_hash[:dboptions].empty?
@property_hash[:dboptions].each_key do |k|
t << case k
when 'dbnosync'
"delete: olcDbNosync\n-\n"
when 'dbpagesize'
"delete: olcDbPagesize\n-\n"
when 'dbconfig'
"delete: olcDbConfig\n-\n"
else
"delete: olcDb#{k}\n-\n"
end
end
end
@property_flush[:dboptions].each do |k, v|
t << case k
when 'dbnosync'
"replace: olcDbNosync\nolcDbNosync: #{v}\n-\n"
when 'dbpagesize'
"replace: olcDbPagesize\nolcDbPagesize: #{v}\n-\n"
when 'dbconfig'
"replace: olcDbConfig\n#{v.map { |x| "olcDbConfig: #{x}" }.join("\n")}\n-\n"
else
if v.is_a?(Array)
"replace: olcDb#{k}\n#{v.map { |x| "olcDb#{k}: #{x}" }.join("\n")}\n-\n"
else
"replace: olcDb#{k}\nolcDb#{k}: #{v}\n-\n"
end
end
end
# rubocop:enable Metrics/BlockNesting
end
t << "replace: olcSyncrepl\n#{resource[:syncrepl].map { |x| "olcSyncrepl: #{x}" }.join("\n")}\n-\n" if @property_flush[:syncrepl]
t << "replace: olcUpdateref\nolcUpdateref: #{resource[:updateref]}\n-\n" if @property_flush[:updateref]
t << "replace: olcMirrorMode\nolcMirrorMode: #{resource[:mirrormode] == :true ? 'TRUE' : 'FALSE'}\n-\n" if @property_flush[:mirrormode]
t << "replace: olcMultiProvider\nolcMultiProvider: #{resource[:multiprovider] == :true ? 'TRUE' : 'FALSE'}\n-\n" if @property_flush[:multiprovider]
t << "replace: olcSyncUseSubentry\nolcSyncUseSubentry: #{resource[:syncusesubentry]}\n-\n" if @property_flush[:syncusesubentry]
t << "replace: olcLimits\n#{@property_flush[:limits].map { |x| "olcLimits: #{x}" }.join("\n")}\n-\n" if @property_flush[:limits]
t << "replace: olcSecurity\n#{@property_flush[:security].map { |k, v| "olcSecurity: #{k}=#{v}" }.join("\n")}\n-\n" if @property_flush[:security]
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
initdb if @property_flush[:directory]
end
@property_hash = resource.to_hash
end
end
@@ -0,0 +1,120 @@
# frozen_string_literal: true
require File.expand_path(File.join(File.dirname(__FILE__), %w[.. openldap]))
# rubocop:disable Naming/VariableName
# rubocop:disable Naming/MethodName
# rubocop:disable Lint/AssignmentInCondition
Puppet::Type.
type(:openldap_dbindex).
provide(:olc, parent: Puppet::Provider::Openldap) do
# TODO: Use ruby bindings (can't find one that support IPC)
defaultfor osfamily: %i[debian freebsd redhat suse]
mk_resource_methods
def self.instances
# TODO: restict to bdb and hdb
i = []
slapcat('(olcDbIndex=*)').split("\n\n").map do |paragraph|
suffix = nil
attrlist = nil
indices = nil
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcSuffix: }
suffix = line.split[1]
when %r{^olcDbIndex: }
attrlist, indices = line.match(%r{^olcDbIndex: (\S+)(?:\s+(.+))?$}).captures
i << new(
name: "#{attrlist} on #{suffix}",
ensure: :present,
attribute: attrlist,
suffix: suffix,
indices: indices
)
end
end
end
i
end
def self.prefetch(resources)
dbindexes = instances
resources.each_key do |name|
next unless provider = dbindexes.find do |access|
access.attribute == resources[name][:attribute] && access.suffix == resources[name][:suffix]
end
resources[name].provider = provider
end
end
def getDn(suffix)
slapcat("(olcSuffix=#{suffix})").split("\n").map do |line|
return line.split[1] if line =~ %r{^dn: }
end
end
def exists?
@property_hash[:ensure] == :present
end
def create
t = Tempfile.new('openldap_dbindex')
t << "dn: #{getDn(resource[:suffix])}\n"
t << "add: olcDbIndex\n"
t << "olcDbIndex: #{resource[:attribute]} #{resource[:indices]}\n"
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
def indices=(_value)
current_olcDbIndex = getCurrentOlcDbIndex(resource[:suffix])
t = Tempfile.new('openldap_dbindex')
t << "dn: #{getDn(resource[:suffix])}\n"
t << "changetype: modify\n"
t << "replace: olcDbIndex\n"
current_olcDbIndex.each do |olc_db_index|
t << if olc_db_index[:attribute].to_s == resource[:attribute].to_s
"olcDbIndex: #{resource[:attribute]} #{resource[:indices]}\n"
else
"olcDbIndex: #{olc_db_index[:attribute]} #{olc_db_index[:indices]}\n"
end
end
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
def getCurrentOlcDbIndex(suffix)
i = []
slapcat('(olcDbIndex=*)', getDn(suffix)).split("\n\n").map do |paragraph|
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcDbIndex: }
attribute, indices = line.match(%r{^olcDbIndex:\s+(\S+)\s+(.*)$}).captures
i << {
attribute: attribute,
indices: indices,
}
end
end
end
i
end
end
# rubocop:enable Naming/VariableName
# rubocop:enable Naming/MethodName
# rubocop:enable Lint/AssignmentInCondition
@@ -0,0 +1,152 @@
# frozen_string_literal: true
require File.expand_path(File.join(File.dirname(__FILE__), %w[.. openldap]))
# rubocop:disable Lint/RescueException
Puppet::Type.
type(:openldap_global_conf).
provide(:olc, parent: Puppet::Provider::Openldap) do
# TODO: Use ruby bindings (can't find one that support IPC)
defaultfor osfamily: %i[debian freebsd redhat suse]
mk_resource_methods
def self.instances
items = slapcat('(objectClass=olcGlobal)')
options = {}
# iterate olc options and removes any keys when it found any duplications
# such as olcServerID
items.gsub("\n ", '').split("\n").grep(%r{^olc}).map do |line|
name, value = line.split(': ')
name = name[3, name.length]
if options[name] && !options[name].is_a?(Array)
options[name] = [options[name]]
options[name].push(value)
elsif options[name]
options[name].push(value)
else
options[name] = value
end
end
new_instances = []
# iterate options and creates new ProviderOlc instances
options.each do |k, v|
new_instances << Puppet::Type::Openldap_global_conf::ProviderOlc.new(
name: k,
ensure: :present,
value: v
)
end
new_instances
end
def self.prefetch(resources)
items = instances
resources.each_key do |name|
if (provider = items.find { |item| item.name.casecmp(name.downcase).zero? })
resources[name].provider = provider
end
end
end
def exists?
if resource[:value].is_a? Hash
(resource[:value].keys - self.class.instances.map(&:name)).empty?
else
@property_hash[:ensure] == :present
end
end
def create
t = Tempfile.new('openldap_global_conf')
t << "dn: cn=config\n"
if resource[:value].is_a? Hash
resource[:value].each do |k, v|
t << "add: olc#{k}\n"
if v.is_a? Array
v.each { |x| t << "olc#{k}: #{x}\n" }
else
t << "olc#{k}: #{v}\n"
end
t << "-\n"
end
else
t << "add: olc#{resource[:name]}\n"
t << "olc#{resource[:name]}: #{resource[:value]}\n"
end
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue Exception => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
@property_hash[:ensure] = :present
end
def destroy
t = Tempfile.new('openldap_global_conf')
t << "dn: cn=config\n"
if resource[:value].is_a? Hash
resource[:value].each_key do |k|
t << "delete: olc#{k}\n"
t << "-\n"
end
else
t << "delete: olc#{name}\n"
end
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue Exception => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
@property_hash.clear
end
def value
if resource[:value].is_a? Hash
instances = self.class.instances
values = resource[:value].map do |k, _v|
found = instances.find { |item| item.name == k }
[k, found.get(:value)] unless found.nil?
end
values.to_h
else
@property_hash[:value]
end
end
def value=(value)
t = Tempfile.new('openldap_global_conf')
t << "dn: cn=config\n"
if resource[:value].is_a? Hash
resource[:value].each do |k, v|
t << "replace: olc#{k}\n"
if v.is_a? Array
v.each { |x| t << "olc#{k}: #{x}\n" }
else
t << "olc#{k}: #{v}\n"
end
t << "-\n"
end
else
t << "replace: olc#{name}\n"
t << "olc#{name}: #{value}\n"
end
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue Exception => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
@property_hash[:value] = value
end
end
# rubocop:enable Lint/RescueException
@@ -0,0 +1,77 @@
# frozen_string_literal: true
require File.expand_path(File.join(File.dirname(__FILE__), %w[.. openldap]))
Puppet::Type.
type(:openldap_module).
provide(:olc, parent: Puppet::Provider::Openldap) do
# TODO: Use ruby bindings (can't find one that support IPC)
defaultfor osfamily: %i[debian freebsd redhat suse]
mk_resource_methods
def self.create_module_list
ldif = temp_ldif('openldap_module')
ldif << "dn: cn=module{0},cn=config\n"
ldif << "changetype: add\n"
ldif << "cn: module\n"
ldif << "objectclass: olcModuleList\n"
ldif.close
begin
ldapmodify(ldif.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{ldif}\nError message: #{e.message}"
end
end
def self.instances
dn = slapcat('(objectClass=olcModuleList)')
create_module_list if dn.empty?
i = []
dn.split("\n\n").map do |paragraph|
paragraph.split("\n").map do |line|
case line
when %r{^olcModuleLoad: }
i << new(
ensure: :present,
name: line.match(%r{^olcModuleLoad: \{\d+\}([^.]+).*$}).captures[0]
)
end
end
end
i
end
def self.prefetch(resources)
mods = instances
resources.each_key do |name|
if (provider = mods.find { |mod| mod.name == name })
resources[name].provider = provider
end
end
end
def exists?
@property_hash[:ensure] == :present
end
def create
t = Tempfile.new('openldap_module')
t << "dn: cn=module{0},cn=config\n"
t << "add: olcModuleLoad\n"
t << "olcModuleLoad: #{resource[:name]}.la\n"
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
@property_hash[:ensure] = :present
end
end
@@ -0,0 +1,224 @@
# frozen_string_literal: true
require File.expand_path(File.join(File.dirname(__FILE__), %w[.. openldap]))
# rubocop:disable Naming/MethodName
# rubocop:disable Lint/RescueException
# rubocop:disable Lint/EmptyWhen
Puppet::Type.
type(:openldap_overlay).
provide(:olc, parent: Puppet::Provider::Openldap) do
# TODO: Use ruby bindings (can't find one that support IPC)
defaultfor osfamily: %i[debian freebsd redhat suse]
mk_resource_methods
def self.instances
slapcat('(olcOverlay=*)').split("\n\n").map do |paragraph|
overlay = nil
suffix = nil
index = nil
options = {}
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^dn: }
index, overlay, database = line.match(%r{^dn: olcOverlay=\{(\d+)\}([^,]+),olcDatabase=([^,]+),cn=config$}).captures
suffix = getSuffix(database)
when %r{^olcOverlay: }i
when %r{^olc(\S+): }i
opt_k, opt_v = line.split(': ', 2)
opt_v = opt_v.split('}', 2)[1] if opt_v =~ %r{^\{\d+\}(.+)$}
if options[opt_k] && !options[opt_k].is_a?(Array)
options[opt_k] = [options[opt_k]]
options[opt_k].push(opt_v)
elsif options[opt_k]
options[opt_k].push(opt_v)
else
options[opt_k] = opt_v
end
end
end
new(
name: "#{overlay} on #{suffix}",
ensure: :present,
overlay: overlay,
suffix: suffix,
index: index.to_i,
options: options.empty? ? nil : options
)
end
end
def self.prefetch(resources)
overlays = instances
resources.each_key do |name|
if (provider = overlays.find { |overlay| overlay.name == name })
resources[name].provider = provider
end
end
end
def exists?
@property_hash[:ensure] == :present
end
def create
overlay_object_class = {
'accesslog' => 'olcAccessLogConfig',
'auditlog' => 'olcAuditLogConfig',
'autoca' => 'olcAutoCAConfig',
'autogroup' => 'olcAutomaticGroups',
'collect' => 'olcCollectConfig',
'constraint' => 'olcConstraintConfig',
'dds' => 'olcDDSConfig',
'dyngroup' => 'olcDGConfig',
'dynlist' => 'olcDynamicList',
'lastbind' => 'olcLastBindConfig',
'memberof' => 'olcMemberOf',
'pcache' => 'olcPcacheConfig',
'ppolicy' => 'olcPPolicyConfig',
'refint' => 'olcRefintConfig',
'remoteauth' => 'olcRemoteAuthCfg',
'retcode' => 'olcRetcodeConfig',
'rwm' => 'olcRwmConfig',
'smbk5pwd' => 'olcSmbK5PwdConfig',
'sock' => 'olcOvSocketConfig',
'sssvlv' => 'olcSssVlvConfig',
'syncprov' => 'olcSyncProvConfig',
'translucent' => 'olcTranslucentConfig',
'unique' => 'olcUniqueConfig',
'valsort' => 'olcValSortConfig',
}.freeze
t = Tempfile.new('openldap_overlay')
t << "dn: olcOverlay=#{resource[:overlay]},#{getDn(resource[:suffix])}\n"
t << "changetype: add\n"
t << "objectClass: olcConfig\n"
t << "objectClass: olcOverlayConfig\n"
t << "objectClass: #{overlay_object_class.fetch(resource[:overlay])}\n"
t << "olcOverlay: #{resource[:overlay]}\n"
resource[:options]&.each do |k, v|
t << if v.is_a?(Array)
v.map { |x| "#{k}: #{x}\n" }.join
else
"#{k}: #{v}\n"
end
end
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue Exception => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
def getDn(suffix)
if suffix == 'cn=config'
if resource[:overlay].to_s == 'rwm'
slapcat('(olcDatabase=relay)').split("\n").map do |line|
return line.split[1] if line =~ %r{^dn: }
end
else
'olcDatabase={0}config,cn=config'
end
else
slapcat("(olcSuffix=#{suffix})").split("\n").map do |line|
return line.split[1] if line =~ %r{^dn: }
end
end
end
def self.getSuffix(database)
found = false
slapcat("(olcDatabase=#{database})").split("\n").map do |line|
found = true if line =~ %r{^dn: olcDatabase=#{database.gsub('{', '\{').gsub('}', '\}')},}
return 'cn=config' if database == '{0}config'
return 'cn=config' if database =~ %r{\{\d+\}relay$}
return line.split[1] if line =~ %r{^olcSuffix: } && found
end
end
def initialize(value = {})
super(value)
@property_flush = {}
end
def options=(value)
@property_flush[:options] = value
end
def flush
unless @property_flush.empty?
t = Tempfile.new('openldap_overlay')
t << "dn: olcOverlay={#{@property_hash[:index]}}#{resource[:overlay]},#{getDn(resource[:suffix])}\n"
t << "changetype: modify\n"
if @property_flush[:options]
# Remove all previously options remove in the should
@property_hash[:options]&.reject { |key, _value| @property_flush[:options].member?(key) }&.each_key do |k|
t << "delete: #{k}\n-\n"
end
# Add current options
@property_flush[:options].each do |k, v|
action = if (@property_hash[:options] || {}).member?(k)
'replace'
else
'add'
end
t << if v.is_a?(Array)
"#{action}: #{k}\n#{v.map { |x| "#{k}: #{x}" }.join("\n")}\n-\n"
else
"#{action}: #{k}\n#{k}: #{v}\n-\n"
end
end
end
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue Exception => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
@property_has = resource.to_hash
end
def getPath(dn)
"#{dn.split(',').reverse.join('/')}.ldif"
end
def destroy
default_confdir = {
'Debian' => '/etc/ldap/slapd.d',
'RedHat' => '/etc/openldap/slapd.d',
'FreeBSD' => '/usr/local/etc/openldap/slapd.d',
}[Facter.value(:osfamily)]
`service slapd stop`
path = "#{default_confdir}/#{getPath("olcOverlay={#{@property_hash[:index]}}#{resource[:overlay]},#{getDn(resource[:suffix])}")}"
File.delete(path)
slapcat('(objectClass=olcOverlayConfig)', getDn(resource[:suffix])).
split("\n").
grep(%r{^dn: }).
select { |dn| dn.match(%r{^dn: olcOverlay=\{(\d+)\}(.+),#{Regexp.quote(getDn(resource[:suffix]))}$}).captures[0].to_i > @property_hash[:index] }.
each do |dn|
index, type = dn.match(%r{^dn: olcOverlay=\{(\d+)\}(.+),#{Regexp.quote(getDn(resource[:suffix]))}$}).captures
index = index.to_i
old_filename = "#{default_confdir}/#{getPath(dn.split(' ', 2)[1])}"
new_filename = "#{default_confdir}/#{getPath("olcOverlay={#{index - 1}}#{type},#{getDn(@property_hash[:suffix])}")}"
File.rename(old_filename, new_filename)
text = File.read(new_filename)
replace = text.gsub("{#{index}}#{type}", "{#{index - 1}}#{type}")
File.open(new_filename, 'w') { |file| file.puts replace }
end
`service slapd start`
@property_hash.clear
end
end
# rubocop:enable Naming/MethodName
# rubocop:enable Lint/RescueException
# rubocop:enable Lint/EmptyWhen
@@ -0,0 +1,227 @@
# frozen_string_literal: true
require 'time'
require File.expand_path(File.join(File.dirname(__FILE__), %w[.. openldap]))
# rubocop:disable Naming/VariableName
# rubocop:disable Naming/MethodName
# rubocop:disable Lint/AssignmentInCondition
# rubocop:disable Style/IfInsideElse
Puppet::Type.
type(:openldap_schema).
provide(:olc, parent: Puppet::Provider::Openldap) do
# TODO: Use ruby bindings (can't find one that support IPC)
defaultfor osfamily: %i[debian freebsd redhat suse]
mk_resource_methods
def self.instances
schemas = []
slapcat('(objectClass=olcSchemaConfig)').split("\n\n").each do |paragraph|
schema = { 'name' => nil, 'index' => nil, 'date' => nil }
paragraph.split("\n").each do |line|
case line
when %r{^cn: \{(\d+)\}(\S+)}
schema['name'] = Regexp.last_match(2).to_s
schema['index'] = Regexp.last_match(1).to_s
when %r{^modifyTimestamp: (\S+)}
schema['date'] = Time.strptime(Regexp.last_match(1).to_s, '%Y%m%d%H%M%S%Z')
end
end
schemas.push(schema) unless schema['name'].nil?
end
schemas.map do |schema|
new(
ensure: :present,
index: schema['index'],
name: schema['name'],
date: schema['date']
)
end
end
def self.schemaToLdif(schema, name)
ldif = [
"dn: cn=#{name},cn=schema,cn=config",
'objectClass: olcSchemaConfig',
"cn: #{name}",
]
schema.split("\n").each do |line|
case line
when %r{^\s*#} # Comments are ok
ldif.push(line)
when %r{^$} # Replace empty lines with comment
ldif.push('#')
when %r{^objectidentifier(.*)$}i # Rewrite tags
ldif.push("olcObjectIdentifier:#{Regexp.last_match(1)}")
when %r{^attributetype(.*)$}i
ldif.push("olcAttributeTypes:#{Regexp.last_match(1)}")
when %r{^objectclass(.*)$}i
ldif.push("olcObjectClasses:#{Regexp.last_match(1)}")
when %r{^\s+(.*)} # Rewrite continuation whitespace
ldif.push(" #{Regexp.last_match(1)}") # One space to indicate continuation, plus one for spacing between words
else
raise Puppet::Error, "Failed to parse schema line in schemaToLdif: '#{line}'"
end
end
ldif.join("\n")
end
def self.schemaToLdifReplace(schema, name)
ldif = [
"dn: cn=#{name},cn=schema,cn=config",
'changetype: modify',
]
objId = []
attrType = []
objClass = []
current = nil
schema.split("\n").each do |line|
case line
when %r{^\s*#}, %r{^$}
next
when %r{^objectidentifier(.*)$}i
current = objId
current.push("olcObjectIdentifier:#{Regexp.last_match(1)}")
when %r{^attributetype(.*)$}i
current = attrType
current.push("olcAttributeTypes:#{Regexp.last_match(1)}")
when %r{^objectclass(.*)$}i
current = objClass
current.push("olcObjectClasses:#{Regexp.last_match(1)}")
when %r{^\s+(.*)}
current&.push(" #{Regexp.last_match(1)}")
else
raise Puppet::Error, "Failed to parse schema line in schemaToLdifReplace: '#{line}'"
end
end
unless objId.empty?
ldif.push('replace: olcObjectIdentifier')
ldif.push(*objId)
ldif.push('-')
end
unless attrType.empty?
ldif.push('replace: olcAttributeTypes')
ldif.push(*attrType)
ldif.push('-')
end
ldif.push('replace: olcObjectClasses')
ldif.push(*objClass)
ldif.push('-')
ldif.join("\n")
end
def self.ldifReplace(ldif, name)
new_ldif = [
"dn: cn=#{name},cn=schema,cn=config",
'changetype: modify',
]
objId = []
attrType = []
objClass = []
current = nil
ldif.split("\n").each do |line|
case line
when %r{^\s*#}, %r{^$}, %r{^dn:}i, %r{^cn:}i, %r{objectClass:}i
next
when %r{^olcObjectIdentifier:\s+(.*)$}i
current = objId
current.push("olcObjectIdentifier:#{Regexp.last_match(1)}")
when %r{^olcAttributeTypes:\s+(.*)$}i
current = attrType
current.push("olcAttributeTypes:#{Regexp.last_match(1)}")
when %r{^olcObjectClasses:\s+(.*)$}i
current = objClass
current.push("olcObjectClasses:#{Regexp.last_match(1)}")
when %r{^\s+(.*)}
current&.push(" #{Regexp.last_match(1)}")
else
raise Puppet::Error, "Failed to parse LDIF line in ldifReplace: '#{line}'"
end
end
unless objId.empty?
new_ldif.push('replace: olcObjectIdentifier')
new_ldif.push(*objId)
new_ldif.push('-')
end
unless attrType.empty?
new_ldif.push('replace: olcAttributeTypes')
new_ldif.push(*attrType)
new_ldif.push('-')
end
new_ldif.push('replace: olcObjectClasses')
new_ldif.push(*objClass)
new_ldif.push('-')
new_ldif.join("\n")
end
def self.prefetch(resources)
existing = instances
resources.each_key do |name|
if provider = existing.find { |r| r.name == name }
resources[name].provider = provider
end
end
end
def create
t = Tempfile.new('openldap_schemas_ldif')
begin
schema = File.read(resource[:path])
file_extention = File.extname(resource[:path])
t << if file_extention == '.schema'
if @property_hash[:ensure] == :present
self.class.schemaToLdifReplace(schema, "{#{@property_hash[:index]}}#{@property_hash[:name]}")
else
self.class.schemaToLdif(schema, resource[:name])
end
else
if @property_hash[:ensure] == :present
self.class.ldifReplace(schema, "{#{@property_hash[:index]}}#{@property_hash[:name]}")
else
schema
end
end
t.close
ldapadd(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
@property_hash[:ensure] = :present
end
def exists?
if resource[:path] && File.file?(resource[:path])
Puppet.debug("#{@property_hash[:name]} date: #{@property_hash[:date]}")
Puppet.debug("#{@property_hash[:name]} mtime: #{File.mtime(resource[:path])}")
timeshift = File.mtime(resource[:path]) - (@property_hash[:date] || 0)
Puppet.debug("#{@property_hash[:name]} timeshift: #{timeshift}")
@property_hash[:ensure] == :present && timeshift.to_i <= 0
else
@property_hash[:ensure] == :present
end
end
def destroy
raise Puppet::Error, 'Removing schemas is not supported by this provider. Slapd needs to be stopped and the schema must be removed manually.'
end
end
# rubocop:enable Naming/VariableName
# rubocop:enable Naming/MethodName
# rubocop:enable Lint/AssignmentInCondition
# rubocop:enable Style/IfInsideElse
@@ -0,0 +1,64 @@
# frozen_string_literal: true
Puppet::Type.newtype(:openldap_access) do
@doc = 'Manages OpenLDAP ACPs/ACLs'
ensurable
newparam(:name) do
desc 'The default namevar'
end
newparam(:target) do
desc 'The slapd.conf file'
end
newparam(:position) do
desc 'Where to place the new entry'
end
newproperty(:what) do
desc 'The entries and/or attributes to which the access applies'
end
newparam(:suffix) do
desc 'The suffix to which the access applies'
end
newproperty(:access, array_matching: :all) do
desc 'Access rule.'
munge do |v|
if v.is_a?(String)
a = []
v.split(%r{(?= by .+)}).each do |b|
a << b.lstrip
end
a
else
v
end
end
def insync?(is)
@should.flatten!
super(is)
end
end
def self.title_patterns
[
[
%r{^((\d+)\s+on\s+(.+))$},
[
[:name],
[:position],
[:suffix],
],
],
]
end
autorequire(:openldap_database) do
[value(:suffix)]
end
end
@@ -0,0 +1,250 @@
# frozen_string_literal: true
require 'puppet/property/boolean'
# rubocop:disable Style/RegexpLiteral
Puppet::Type.newtype(:openldap_database) do
@doc = 'Manages OpenLDAP BDB and HDB databases.'
ensurable
newparam(:suffix, namevar: true) do
desc 'The default namevar.'
validate do |value|
raise ArgumentError, 'Invalid value' unless value.match?(%r{\A[[:alnum:]]+=[^,;]+([,;][[:alnum:]]+=[^,;]+)*\z})
end
end
newparam(:relay) do
desc 'The relay configuration.'
end
newparam(:target)
newproperty(:index) do
desc 'The index of the database.'
end
newproperty(:backend) do
desc 'The name of the backend.'
newvalues('bdb', 'hdb', 'mdb', 'monitor', 'config', 'relay', 'ldap')
defaultto do
case Facter.value(:osfamily)
when 'Debian'
case Facter.value(:operatingsystem)
when 'Debian'
if Facter.value(:operatingsystemmajrelease).to_i <= 7
'hdb'
else
'mdb'
end
when 'Ubuntu'
if Facter.value(:operatingsystemmajrelease).to_i <= 15
'hdb'
else
'mdb'
end
else
'hdb'
end
when 'RedHat'
if Facter.value(:operatingsystemmajrelease).to_i <= 6
'bdb'
elsif Facter.value(:os).dig('release', 'major').to_i >= 9
'mdb'
else
'hdb'
end
when 'FreeBSD'
'mdb'
end
end
end
newproperty(:directory) do
desc 'The directory where the BDB files containing this database and associated indexes live.'
defaultto do
'/var/lib/ldap' unless %w[monitor config relay ldap].include? (@resource[:backend]).to_s
end
validate do |value|
raise ArgumentError, 'Invalid value' unless value.start_with?('/')
end
end
newproperty(:rootdn) do
desc 'The distinguished name that is not subject to access control or administrative limit restrictions for operations on this database.'
end
newproperty(:rootpw) do
desc 'Password (or hash of the password) for the rootdn.'
def insync?(is)
if should =~ %r{^\{(CRYPT|MD5|SMD5|SSHA|SHA(256|384|512)?)\}.+}
should == is
else
case is
when %r{^\{CRYPT\}.+}
"{CRYPT}#{should.crypt(is[0, 2])}" == is
when %r{^\{MD5\}.+}
"{MD5}#{Digest::MD5.hexdigest(should)}" == is
when %r{^\{SMD5\}.+}
salt = is[16..]
md5_hash_with_salt = "#{Digest::MD5.digest(should + salt)}#{salt}"
is == "{SMD5}#{[md5_hash_with_salt].pack('m').delete("\n")}"
when %r{^\{SSHA\}.+}
decoded = Base64.decode64(is.gsub(%r{^\{SSHA\}}, ''))
salt = decoded[20..]
"{SSHA}#{Base64.encode64("#{Digest::SHA1.digest("#{should}#{salt}")}#{salt}").chomp}" == is
when %r{^\{SHA\}.+}
"{SHA}#{Digest::SHA1.hexdigest(should)}" == is
when %r{^\{(SHA(256|384|512))\}}
matches = is.match('^{(SHA[\\d]{,3})}')
raise ArgumentError, "Invalid password format: #{is}" if matches.nil?
crypto = matches[1]
case crypto
when 'SHA256'
"{SHA256}#{Digest::SHA256.hexdigest(should)}" == is
when 'SHA384'
"{SHA384}#{Digest::SHA384.hexdigest(should)}" == is
when 'SHA512'
"{SHA512}#{Digest::SHA512.hexdigest(should)}" == is
end
else
false
end
end
end
def sync
require 'securerandom'
salt = SecureRandom.random_bytes(4)
@resource[:rootpw] = if should =~ %r{^\{(CRYPT|MD5|SMD5|SSHA|SHA(256|384|512)?)\}.+}
should
else
"{SSHA}#{Base64.encode64("#{Digest::SHA1.digest("#{should}#{salt}")}#{salt}").chomp}"
end
super
end
def change_to_s(currentvalue, _newvalue)
if currentvalue == :absent
'created password'
else
'changed password'
end
end
def is_to_s(_currentvalue)
'[old password hash redacted]'
end
def should_to_s(_newvalue)
'[new password hash redacted]'
end
end
newparam(:initdb, boolean: true) do
desc 'When true it initiales the database with the top object. When false, it does not create any object in the database, so you have to create it by other mechanism. It defaults to false when the backend is one of config, ldap, monitor or relay, true otherwise.'
newvalues(:true, :false)
defaultto do
if %w[monitor config relay ldap].include? (@resource[:backend]).to_s
:false
else
:true
end
end
end
newparam(:organization) do
desc 'Organization name used when initdb is true'
defaultto do
@resource[:suffix].split(/,?dc=/).delete_if(&:empty?).join('.') if @resource[:suffix].start_with?('dc=')
end
end
newproperty(:readonly) do
desc 'Puts the database into read-only mode.'
end
newproperty(:sizelimit) do
desc 'Specifies the maximum number of entries to return from a search operation.'
end
newproperty(:dbmaxsize) do
desc 'Specifies the maximum size of the DB in bytes.'
end
newproperty(:timelimit) do
desc 'Specifies the maximum number of seconds (in real time) slapd will spend answering a search request.'
end
newproperty(:updateref) do
desc 'This directive is only applicable in a slave slapd. It specifies the URL to return to clients which submit update requests upon the replica.'
end
newproperty(:dboptions) do
desc 'Hash to pass specific HDB/BDB options for the database'
def insync?(is)
if resource[:synctype] == :inclusive
is == should
else
should.each do |k, _v|
return false if is[k] != should[k]
end
end
end
end
newparam(:synctype) do
desc "Whether specified dboptions should be considered the complete list (inclusive) or the minimum list (minimum) of dboptions the database should have. Defaults to minimum.
Valid values are inclusive, minimum."
newvalues(:inclusive, :minimum)
defaultto :minimum
end
newproperty(:mirrormode, boolean: true) do
desc 'This option puts a replica database into "mirror" mode, deprecated as of 2.5'
newvalues(:true, :false)
end
newproperty(:multiprovider, boolean: true) do
desc 'This option puts a replica database into "multiprovider" mode'
newvalues(:true, :false)
end
newproperty(:syncusesubentry) do
desc 'Store the syncrepl contextCSN in a subentry instead of the context entry of the database'
end
newproperty(:syncrepl, array_matching: :all) do
desc 'Specify the current database as a replica which is kept up-to-date with the master content by establishing the current slapd(8) as a replication consumer site running a syncrepl replication engine.'
end
newproperty(:limits, array_matching: :all) do
desc 'Limits the number entries returned and/or the time spent by a request'
validate do |value|
raise ArgumentError, "Invalid limit: #{value}\nLimit values must be according to syntax described at http://www.openldap.org/doc/admin24/limits.html#Per-Database%20Limits" if value !~ /^(\*|anonymous|users|self|(dn(\.\S+)?=\S+)|(dn\.\S+=\S+)|(group(\/\S+(\/\S+)?)?=\S+))(\s+((time(\.(soft|hard))?=((\d+)|unlimited))|(size(\.(soft|hard|unchecked))?=((\d+)|unlimited))|(size\.pr=((\d+)|noEstimate|unlimited))|(size.prtotal=((\d+)|unlimited|disabled))))+$/
end
end
newproperty(:security) do
desc 'The olcSecurity configuration.'
correct_keys = %w[transport sasl simple_bind ssf tls update_sasl update_ssf update_tls update_transport]
validate do |value|
value.each do |k, v|
raise ArgumentError, "Invalid security key: '#{k}' for value '#{v}'\nSecurity key must be one of these value: #{correct_keys.join(', ')}\nSee olcSecurity in `man slapd-config`" unless correct_keys.include? k
next if Float(v)
raise ArgumentError, "Invalid security value: '#{v}' for key '#{k}'\nSecurity value must be a number\nSee olcSecurity in `man slapd-config`"
end
end
end
end
# rubocop:enable Style/RegexpLiteral
@@ -0,0 +1,51 @@
# frozen_string_literal: true
Puppet::Type.newtype(:openldap_dbindex) do
@doc = 'Manages OpenLDAP DB indexes'
ensurable
newparam(:name) do
desc 'The default namevar'
end
newparam(:target) do
desc 'The slapd.conf file'
end
newparam(:suffix, namevar: true) do
desc 'The suffix to which the index applies'
end
newparam(:attribute, namevar: true) do
desc 'The attribute to index'
defaultto('default')
end
def self.title_patterns
[
[
%r{^((\S+)\s+on\s+(.+))$},
[
[:name],
[:attribute],
[:suffix],
],
],
[
%r{(.*)},
[
[:name],
],
],
]
end
newproperty(:indices) do
desc 'The indices to maintain'
end
autorequire(:openldap_database) do
[value(:suffix)]
end
end
@@ -0,0 +1,15 @@
# frozen_string_literal: true
Puppet::Type.newtype(:openldap_global_conf) do
ensurable
newparam(:name)
newparam(:target)
newproperty(:value) do
validate do |value|
raise Puppet::Error, 'value should be a String or a Hash' unless [String, Hash].include? value.class
end
end
end
@@ -0,0 +1,13 @@
# frozen_string_literal: true
Puppet::Type.newtype(:openldap_module) do
@doc = 'Manages OpenLDAP modules.'
ensurable
newparam(:name) do
desc 'The default namevar.'
end
newparam(:target)
end
@@ -0,0 +1,50 @@
# frozen_string_literal: true
Puppet::Type.newtype(:openldap_overlay) do
@doc = 'Manages OpenLDAP Overlays'
ensurable
newparam(:name) do
desc 'The default namevar'
end
newparam(:target) do
desc 'The slapd.conf file'
end
newproperty(:index) do
desc 'The index of the overlay.'
end
newparam(:overlay, namevar: true) do
desc 'The name of the overlay to apply'
end
newparam(:suffix, namevar: true) do
desc 'The suffix to which the overlay applies'
end
def self.title_patterns
[
[
%r{^((\S+)\s+on\s+(\S+))$},
[
[:name],
[:overlay],
[:suffix],
],
],
[
%r{(.*)},
[
[:name],
],
],
]
end
newproperty(:options) do
desc 'Overlay options.'
end
end
@@ -0,0 +1,26 @@
# frozen_string_literal: true
Puppet::Type.newtype(:openldap_schema) do
@doc = 'Manages OpenLDAP schemas.'
ensurable
newparam(:name) do
desc 'The default namevar.'
end
newparam(:path) do
desc 'The location to the schema file.'
validate do |value|
raise("Invalid file type #{value}") unless value =~ %r{.*(\.ldif|\.schema)$}i
end
end
newproperty(:index) do
desc 'The index of the schema.'
end
newproperty(:date) do
desc 'The modifyTimestamp of the schema.'
end
end
+44
View File
@@ -0,0 +1,44 @@
# This file was automatically generated on 2026-11-08 22:33:58 +1100.
# Use the 'puppet generate types' command to regenerate this file.
# Manages OpenLDAP ACPs/ACLs
Puppet::Resource::ResourceType3.new(
'openldap_access',
[
# The basic property that the resource should be in.
#
# Valid values are `present`, `absent`.
Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'),
# The entries and/or attributes to which the access applies
Puppet::Resource::Param(Any, 'what'),
# Access rule.
Puppet::Resource::Param(Any, 'access')
],
[
# The default namevar
Puppet::Resource::Param(Any, 'name'),
# The slapd.conf file
Puppet::Resource::Param(Any, 'target'),
# Where to place the new entry
Puppet::Resource::Param(Any, 'position'),
# The suffix to which the access applies
Puppet::Resource::Param(Any, 'suffix'),
# The specific backend to use for this `openldap_access`
# resource. You will seldom need to specify this --- OpenVox will usually
# discover the appropriate provider for your platform.Available providers are:
#
# olc
# : * Default for `osfamily` == `debian, freebsd, redhat, suse`.
Puppet::Resource::Param(Any, 'provider')
],
{
/^((\d+)\s+on\s+(.+))$/ => ['name', 'position', 'suffix']
},
true,
false)
+106
View File
@@ -0,0 +1,106 @@
# This file was automatically generated on 2026-11-08 22:33:58 +1100.
# Use the 'puppet generate types' command to regenerate this file.
# Manages OpenLDAP BDB and HDB databases.
Puppet::Resource::ResourceType3.new(
'openldap_database',
[
# The basic property that the resource should be in.
#
# Valid values are `present`, `absent`.
Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'),
# The index of the database.
Puppet::Resource::Param(Any, 'index'),
# The name of the backend.
#
# Valid values are `bdb`, `hdb`, `mdb`, `monitor`, `config`, `relay`, `ldap`.
Puppet::Resource::Param(Enum['bdb', 'hdb', 'mdb', 'monitor', 'config', 'relay', 'ldap'], 'backend'),
# The directory where the BDB files containing this database and associated indexes live.
Puppet::Resource::Param(Any, 'directory'),
# The distinguished name that is not subject to access control or administrative limit restrictions for operations on this database.
Puppet::Resource::Param(Any, 'rootdn'),
# Password (or hash of the password) for the rootdn.
Puppet::Resource::Param(Any, 'rootpw'),
# Puts the database into read-only mode.
Puppet::Resource::Param(Any, 'readonly'),
# Specifies the maximum number of entries to return from a search operation.
Puppet::Resource::Param(Any, 'sizelimit'),
# Specifies the maximum size of the DB in bytes.
Puppet::Resource::Param(Any, 'dbmaxsize'),
# Specifies the maximum number of seconds (in real time) slapd will spend answering a search request.
Puppet::Resource::Param(Any, 'timelimit'),
# This directive is only applicable in a slave slapd. It specifies the URL to return to clients which submit update requests upon the replica.
Puppet::Resource::Param(Any, 'updateref'),
# Hash to pass specific HDB/BDB options for the database
Puppet::Resource::Param(Any, 'dboptions'),
# This option puts a replica database into "mirror" mode, deprecated as of 2.5
#
# Valid values are `true`, `false`.
Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'mirrormode'),
# This option puts a replica database into "multiprovider" mode
#
# Valid values are `true`, `false`.
Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'multiprovider'),
# Store the syncrepl contextCSN in a subentry instead of the context entry of the database
Puppet::Resource::Param(Any, 'syncusesubentry'),
# Specify the current database as a replica which is kept up-to-date with the master content by establishing the current slapd(8) as a replication consumer site running a syncrepl replication engine.
Puppet::Resource::Param(Any, 'syncrepl'),
# Limits the number entries returned and/or the time spent by a request
Puppet::Resource::Param(Any, 'limits'),
# The olcSecurity configuration.
Puppet::Resource::Param(Any, 'security')
],
[
# The default namevar.
Puppet::Resource::Param(Any, 'suffix', true),
# The relay configuration.
Puppet::Resource::Param(Any, 'relay'),
Puppet::Resource::Param(Any, 'target'),
# When true it initiales the database with the top object. When false, it does not create any object in the database, so you have to create it by other mechanism. It defaults to false when the backend is one of config, ldap, monitor or relay, true otherwise.
#
# Valid values are `true`, `false`.
Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'initdb'),
# Organization name used when initdb is true
Puppet::Resource::Param(Any, 'organization'),
# Whether specified dboptions should be considered the complete list (inclusive) or the minimum list (minimum) of dboptions the database should have. Defaults to minimum.
#
# Valid values are inclusive, minimum.
#
# Valid values are `inclusive`, `minimum`.
Puppet::Resource::Param(Enum['inclusive', 'minimum'], 'synctype'),
# The specific backend to use for this `openldap_database`
# resource. You will seldom need to specify this --- OpenVox will usually
# discover the appropriate provider for your platform.Available providers are:
#
# olc
# : * Default for `osfamily` == `debian, freebsd, redhat, suse`.
Puppet::Resource::Param(Any, 'provider')
],
{
/(?m-ix:(.*))/ => ['suffix']
},
true,
false)
+42
View File
@@ -0,0 +1,42 @@
# This file was automatically generated on 2026-11-08 22:33:58 +1100.
# Use the 'puppet generate types' command to regenerate this file.
# Manages OpenLDAP DB indexes
Puppet::Resource::ResourceType3.new(
'openldap_dbindex',
[
# The basic property that the resource should be in.
#
# Valid values are `present`, `absent`.
Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'),
# The indices to maintain
Puppet::Resource::Param(Any, 'indices')
],
[
# The default namevar
Puppet::Resource::Param(Any, 'name'),
# The slapd.conf file
Puppet::Resource::Param(Any, 'target'),
# The suffix to which the index applies
Puppet::Resource::Param(Any, 'suffix', true),
# The attribute to index
Puppet::Resource::Param(Any, 'attribute', true),
# The specific backend to use for this `openldap_dbindex`
# resource. You will seldom need to specify this --- OpenVox will usually
# discover the appropriate provider for your platform.Available providers are:
#
# olc
# : * Default for `osfamily` == `debian, freebsd, redhat, suse`.
Puppet::Resource::Param(Any, 'provider')
],
{
/^((\S+)\s+on\s+(.+))$/ => ['name', 'attribute', 'suffix'],
/(.*)/ => ['name']
},
true,
false)
@@ -0,0 +1,31 @@
# This file was automatically generated on 2026-11-08 22:33:58 +1100.
# Use the 'puppet generate types' command to regenerate this file.
Puppet::Resource::ResourceType3.new(
'openldap_global_conf',
[
# The basic property that the resource should be in.
#
# Valid values are `present`, `absent`.
Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'),
Puppet::Resource::Param(Any, 'value')
],
[
Puppet::Resource::Param(Any, 'name'),
Puppet::Resource::Param(Any, 'target'),
# The specific backend to use for this `openldap_global_conf`
# resource. You will seldom need to specify this --- OpenVox will usually
# discover the appropriate provider for your platform.Available providers are:
#
# olc
# : * Default for `osfamily` == `debian, freebsd, redhat, suse`.
Puppet::Resource::Param(Any, 'provider')
],
{
/(?m-ix:(.*))/ => ['name']
},
true,
false)
+31
View File
@@ -0,0 +1,31 @@
# This file was automatically generated on 2026-11-08 22:33:58 +1100.
# Use the 'puppet generate types' command to regenerate this file.
# Manages OpenLDAP modules.
Puppet::Resource::ResourceType3.new(
'openldap_module',
[
# The basic property that the resource should be in.
#
# Valid values are `present`, `absent`.
Puppet::Resource::Param(Enum['present', 'absent'], 'ensure')
],
[
# The default namevar.
Puppet::Resource::Param(Any, 'name'),
Puppet::Resource::Param(Any, 'target'),
# The specific backend to use for this `openldap_module`
# resource. You will seldom need to specify this --- OpenVox will usually
# discover the appropriate provider for your platform.Available providers are:
#
# olc
# : * Default for `osfamily` == `debian, freebsd, redhat, suse`.
Puppet::Resource::Param(Any, 'provider')
],
{
/(?m-ix:(.*))/ => ['name']
},
true,
false)
+45
View File
@@ -0,0 +1,45 @@
# This file was automatically generated on 2026-11-08 22:33:58 +1100.
# Use the 'puppet generate types' command to regenerate this file.
# Manages OpenLDAP Overlays
Puppet::Resource::ResourceType3.new(
'openldap_overlay',
[
# The basic property that the resource should be in.
#
# Valid values are `present`, `absent`.
Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'),
# The index of the overlay.
Puppet::Resource::Param(Any, 'index'),
# Overlay options.
Puppet::Resource::Param(Any, 'options')
],
[
# The default namevar
Puppet::Resource::Param(Any, 'name'),
# The slapd.conf file
Puppet::Resource::Param(Any, 'target'),
# The name of the overlay to apply
Puppet::Resource::Param(Any, 'overlay', true),
# The suffix to which the overlay applies
Puppet::Resource::Param(Any, 'suffix', true),
# The specific backend to use for this `openldap_overlay`
# resource. You will seldom need to specify this --- OpenVox will usually
# discover the appropriate provider for your platform.Available providers are:
#
# olc
# : * Default for `osfamily` == `debian, freebsd, redhat, suse`.
Puppet::Resource::Param(Any, 'provider')
],
{
/^((\S+)\s+on\s+(\S+))$/ => ['name', 'overlay', 'suffix'],
/(.*)/ => ['name']
},
true,
false)
+38
View File
@@ -0,0 +1,38 @@
# This file was automatically generated on 2026-11-08 22:33:58 +1100.
# Use the 'puppet generate types' command to regenerate this file.
# Manages OpenLDAP schemas.
Puppet::Resource::ResourceType3.new(
'openldap_schema',
[
# The basic property that the resource should be in.
#
# Valid values are `present`, `absent`.
Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'),
# The index of the schema.
Puppet::Resource::Param(Any, 'index'),
# The modifyTimestamp of the schema.
Puppet::Resource::Param(Any, 'date')
],
[
# The default namevar.
Puppet::Resource::Param(Any, 'name'),
# The location to the schema file.
Puppet::Resource::Param(Any, 'path'),
# The specific backend to use for this `openldap_schema`
# resource. You will seldom need to specify this --- OpenVox will usually
# discover the appropriate provider for your platform.Available providers are:
#
# olc
# : * Default for `osfamily` == `debian, freebsd, redhat, suse`.
Puppet::Resource::Param(Any, 'provider')
],
{
/(?m-ix:(.*))/ => ['name']
},
true,
false)