or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

abstract.mdconfig.mdconnection.mdextended.mdindex.mdoperations.md

connection.mddocs/

0

# Core Connection and Server Management

1

2

Server definition, connection establishment, authentication methods, TLS/SSL configuration, server pooling for high availability, and connection strategies for different use cases.

3

4

## Capabilities

5

6

### Server Definition

7

8

Defines LDAP server connection parameters including hostname, port, SSL settings, and server information retrieval options.

9

10

```python { .api }

11

class Server:

12

def __init__(self, host, port=None, use_ssl=False, allowed_referral_hosts=None,

13

get_info=NONE, tls=None, formatter=None, connect_timeout=None,

14

mode=IP_V6_PREFERRED):

15

"""

16

Define an LDAP server.

17

18

Args:

19

host (str): Server hostname or IP address

20

port (int, optional): Server port (389 for LDAP, 636 for LDAPS)

21

use_ssl (bool): Use SSL/TLS connection

22

allowed_referral_hosts (list, optional): Allowed hosts for referrals

23

get_info (str): Server info to retrieve (NONE, DSA, SCHEMA, ALL)

24

tls (Tls, optional): TLS configuration object

25

formatter (dict, optional): Custom formatters for attributes

26

connect_timeout (float, optional): Connection timeout in seconds

27

mode (str): IP addressing mode preference

28

"""

29

30

def check_availability(self):

31

"""

32

Check if server is available.

33

34

Returns:

35

bool: True if server is reachable

36

"""

37

38

def get_info_from_server(self, connection):

39

"""

40

Retrieve server information.

41

42

Args:

43

connection (Connection): Active LDAP connection

44

45

Returns:

46

bool: True if information retrieved successfully

47

"""

48

49

@staticmethod

50

def from_definition(host, dsa_info, dsa_schema, port=None, use_ssl=False,

51

tls=None, formatter=None):

52

"""

53

Create server from DSA definition.

54

55

Args:

56

host (str): Server hostname

57

dsa_info (DsaInfo): DSA information object

58

dsa_schema (SchemaInfo): Schema information object

59

port (int, optional): Server port

60

use_ssl (bool): Use SSL connection

61

tls (Tls, optional): TLS configuration

62

formatter (dict, optional): Custom formatters

63

64

Returns:

65

Server: Configured server object

66

"""

67

```

68

69

**Properties**:

70

- `host`: Server hostname or IP address

71

- `port`: Server port number

72

- `ssl`: SSL enabled flag

73

- `name`: Complete server URL

74

- `tls`: TLS configuration object

75

- `info`: DSA information (DsaInfo instance)

76

- `schema`: Schema information (SchemaInfo instance)

77

- `current_address`: Current connection address

78

79

### Connection Management

80

81

Manages LDAP connections with various authentication methods, client strategies, and connection options.

82

83

```python { .api }

84

class Connection:

85

def __init__(self, server, user=None, password=None, auto_bind=AUTO_BIND_NONE,

86

version=3, authentication=None, client_strategy=SYNC,

87

auto_referrals=True, auto_range=False, sasl_mechanism=None,

88

sasl_credentials=None, check_names=True, collect_usage=False,

89

read_only=False, lazy=False, raise_exceptions=False,

90

pool_name=None, pool_size=None, pool_lifetime=None,

91

fast_decoder=True, receive_timeout=None,

92

return_empty_attributes=False):

93

"""

94

Create LDAP connection.

95

96

Args:

97

server (Server): Server or ServerPool object

98

user (str, optional): User DN for binding

99

password (str, optional): Password for binding

100

auto_bind (str): Auto-bind behavior (NONE, NO_TLS, TLS_BEFORE_BIND, TLS_AFTER_BIND)

101

version (int): LDAP protocol version (default: 3)

102

authentication (str, optional): Authentication method (ANONYMOUS, SIMPLE, SASL, NTLM)

103

client_strategy (str): Client strategy (SYNC, ASYNC, LDIF, RESTARTABLE, REUSABLE)

104

auto_referrals (bool): Follow referrals automatically

105

auto_range (bool): Automatic range retrieval for multi-valued attributes

106

sasl_mechanism (str, optional): SASL mechanism name

107

sasl_credentials (tuple, optional): SASL credentials

108

check_names (bool): Check attribute and object class names (default: True)

109

collect_usage (bool): Collect connection usage statistics

110

read_only (bool): Connection is read-only

111

lazy (bool): Lazy connection - connect on first operation (default: False)

112

raise_exceptions (bool): Raise exceptions for LDAP errors

113

pool_name (str, optional): Connection pool name for REUSABLE strategy

114

pool_size (int, optional): Connection pool size

115

pool_lifetime (int, optional): Connection lifetime in seconds

116

fast_decoder (bool): Use fast BER decoder

117

receive_timeout (float, optional): Receive timeout in seconds

118

return_empty_attributes (bool): Return empty attributes in results (default: False)

119

"""

120

121

def bind(self, user=None, password=None, sasl_mechanism=None, sasl_credentials=None):

122

"""

123

Bind to LDAP server.

124

125

Args:

126

user (str, optional): User DN to bind with

127

password (str, optional): Password for binding

128

sasl_mechanism (str, optional): SASL mechanism

129

sasl_credentials (tuple, optional): SASL credentials

130

131

Returns:

132

bool: True if bind successful

133

"""

134

135

def rebind(self, user=None, password=None, sasl_mechanism=None, sasl_credentials=None):

136

"""

137

Rebind with new credentials.

138

139

Args:

140

user (str, optional): New user DN

141

password (str, optional): New password

142

sasl_mechanism (str, optional): SASL mechanism

143

sasl_credentials (tuple, optional): SASL credentials

144

145

Returns:

146

bool: True if rebind successful

147

"""

148

149

def unbind(self, controls=None):

150

"""

151

Unbind from server and close connection.

152

153

Args:

154

controls (list, optional): LDAP controls

155

156

Returns:

157

bool: True if unbind successful

158

"""

159

160

def start_tls(self):

161

"""

162

Start TLS encryption on connection.

163

164

Returns:

165

bool: True if TLS started successfully

166

"""

167

168

def do_sasl_bind(self, controls):

169

"""

170

Perform SASL bind operation.

171

172

Args:

173

controls (list): LDAP controls for bind

174

175

Returns:

176

bool: True if SASL bind successful

177

"""

178

179

def do_ntlm_bind(self, controls):

180

"""

181

Perform NTLM bind operation.

182

183

Args:

184

controls (list): LDAP controls for bind

185

186

Returns:

187

bool: True if NTLM bind successful

188

"""

189

```

190

191

**Properties**:

192

- `server`: Associated Server or ServerPool object

193

- `user`: Bound user DN

194

- `password`: User password (masked)

195

- `authentication`: Authentication method used

196

- `version`: LDAP protocol version

197

- `auto_bind`: Auto-bind setting

198

- `strategy`: Connection strategy object

199

- `bound`: True if connection is bound

200

- `closed`: True if connection is closed

201

- `usage`: Usage statistics (if enabled)

202

- `entries`: Search result entries (abstract layer)

203

- `response`: Last operation response

204

- `result`: Last operation result

205

206

### TLS/SSL Configuration

207

208

Configures SSL/TLS encryption for secure LDAP connections with certificate validation and client certificate support.

209

210

```python { .api }

211

class Tls:

212

def __init__(self, local_private_key_file=None, local_certificate_file=None,

213

validate=ssl.CERT_NONE, version=None, ca_certs_file=None,

214

valid_names=None, ca_certs_path=None, ca_certs_data=None,

215

local_private_key_password=None):

216

"""

217

Configure TLS/SSL settings.

218

219

Args:

220

local_private_key_file (str, optional): Client private key file path

221

local_certificate_file (str, optional): Client certificate file path

222

validate (int): Certificate validation level (ssl.CERT_NONE, ssl.CERT_OPTIONAL, ssl.CERT_REQUIRED)

223

version (int, optional): SSL/TLS protocol version

224

ca_certs_file (str, optional): CA certificates file path

225

valid_names (list, optional): Valid server names for certificate checking

226

ca_certs_path (str, optional): CA certificates directory path

227

ca_certs_data (str, optional): CA certificates as string data

228

local_private_key_password (str, optional): Private key password

229

"""

230

231

def wrap_socket(self, connection, do_handshake=False):

232

"""

233

Wrap socket with SSL/TLS.

234

235

Args:

236

connection (Connection): LDAP connection object

237

do_handshake (bool): Perform SSL handshake immediately

238

239

Returns:

240

ssl.SSLSocket: Wrapped SSL socket

241

"""

242

243

def start_tls(self, connection):

244

"""

245

Start TLS on existing connection.

246

247

Args:

248

connection (Connection): LDAP connection object

249

250

Returns:

251

bool: True if TLS started successfully

252

"""

253

```

254

255

### Server Pooling

256

257

Manages multiple LDAP servers for high availability with different pooling strategies and automatic failover.

258

259

```python { .api }

260

class ServerPool:

261

def __init__(self, servers=None, pool_strategy=ROUND_ROBIN, active=True, exhaust=False):

262

"""

263

Create server pool for high availability.

264

265

Args:

266

servers (list, optional): List of Server objects

267

pool_strategy (str): Pooling strategy (FIRST, ROUND_ROBIN, RANDOM)

268

active (bool): Check server availability before use

269

exhaust (bool): Try all servers before giving up

270

"""

271

272

def add(self, servers):

273

"""

274

Add server(s) to pool.

275

276

Args:

277

servers (Server or list): Server object(s) to add

278

"""

279

280

def remove(self, server):

281

"""

282

Remove server from pool.

283

284

Args:

285

server (Server): Server object to remove

286

"""

287

288

def initialize(self, connection):

289

"""

290

Initialize pool state for connection.

291

292

Args:

293

connection (Connection): LDAP connection object

294

"""

295

296

def get_server(self, connection):

297

"""

298

Get next server from pool.

299

300

Args:

301

connection (Connection): LDAP connection object

302

303

Returns:

304

Server: Selected server object

305

"""

306

307

def get_current_server(self, connection):

308

"""

309

Get current server for connection.

310

311

Args:

312

connection (Connection): LDAP connection object

313

314

Returns:

315

Server: Current server object

316

"""

317

```

318

319

### Context Manager Support

320

321

```python { .api }

322

# Connection class context manager methods

323

def __enter__(self):

324

"""Enter connection context."""

325

326

def __exit__(self, exc_type, exc_val, exc_tb):

327

"""Exit connection context and close connection."""

328

```

329

330

### Connection Management

331

332

Additional connection management methods for advanced use cases.

333

334

```python { .api }

335

def rebind(self, user=None, password=None, authentication=None, sasl_mechanism=None, sasl_credentials=None):

336

"""

337

Rebind connection with new credentials.

338

339

Args:

340

user (str, optional): New user DN for binding

341

password (str, optional): New password for binding

342

authentication (str, optional): Authentication method

343

sasl_mechanism (str, optional): SASL mechanism for SASL authentication

344

sasl_credentials (tuple, optional): SASL credentials

345

346

Returns:

347

bool: True if rebind successful

348

"""

349

350

def refresh_server_info(self):

351

"""

352

Refresh server information from DSE.

353

354

Returns:

355

bool: True if server info refreshed successfully

356

"""

357

358

@property

359

def entries(self):

360

"""

361

Get search results as Entry objects (abstract layer).

362

363

Returns:

364

list: List of Entry objects from last search

365

"""

366

367

@property

368

def stream(self):

369

"""

370

Get or set connection stream object.

371

372

Returns:

373

object: Current stream object

374

"""

375

376

@stream.setter

377

def stream(self, value):

378

"""Set connection stream object."""

379

380

def extended(self, request_name, request_value=None, controls=None, no_encode=None):

381

"""

382

Perform extended LDAP operation.

383

384

Args:

385

request_name (str): Extended operation OID

386

request_value (bytes, optional): Request value

387

controls (list, optional): LDAP controls

388

no_encode (bool, optional): Skip request value encoding

389

390

Returns:

391

bool: True if operation successful

392

"""

393

```

394

395

### Response Format Conversion

396

397

Methods to convert search responses to different formats.

398

399

```python { .api }

400

def response_to_ldif(self, search_result=None, all_base64=False, line_separator=None, sort_order=None, stream=None):

401

"""

402

Convert response to LDIF format.

403

404

Args:

405

search_result (list, optional): Search results to convert (defaults to last response)

406

all_base64 (bool): Encode all values in base64

407

line_separator (str, optional): Line separator character

408

sort_order (callable, optional): Sort function for entries

409

stream (file, optional): Stream to write LDIF to

410

411

Returns:

412

str: LDIF formatted response

413

"""

414

415

def response_to_json(self, raw=False, search_result=None, indent=4, sort=True, stream=None, checked_attributes=True):

416

"""

417

Convert response to JSON format.

418

419

Args:

420

raw (bool): Include raw attribute values

421

search_result (list, optional): Search results to convert

422

indent (int): JSON indentation level

423

sort (bool): Sort JSON keys

424

stream (file, optional): Stream to write JSON to

425

checked_attributes (bool): Use schema checking for attributes

426

427

Returns:

428

str: JSON formatted response

429

"""

430

431

def response_to_file(self, target, raw=False, encoding='utf-8'):

432

"""

433

Write response to file.

434

435

Args:

436

target (str): Target file path

437

raw (bool): Include raw attribute values

438

encoding (str): File encoding

439

"""

440

```

441

442

## Usage Examples

443

444

### Basic Connection

445

446

```python

447

import ldap3

448

449

# Simple connection

450

server = ldap3.Server('ldap.example.com')

451

conn = ldap3.Connection(server, 'cn=user,dc=example,dc=com', 'password')

452

conn.bind()

453

# ... perform operations

454

conn.unbind()

455

```

456

457

### Secure Connection with TLS

458

459

```python

460

import ldap3

461

462

# TLS configuration

463

tls_config = ldap3.Tls(validate=ssl.CERT_REQUIRED, ca_certs_file='/path/to/ca-certs.pem')

464

server = ldap3.Server('ldap.example.com', use_ssl=True, tls=tls_config)

465

conn = ldap3.Connection(server, 'cn=user,dc=example,dc=com', 'password', auto_bind=True)

466

```

467

468

### Server Pool for High Availability

469

470

```python

471

import ldap3

472

473

# Multiple servers with round-robin

474

server1 = ldap3.Server('ldap1.example.com')

475

server2 = ldap3.Server('ldap2.example.com')

476

server_pool = ldap3.ServerPool([server1, server2], ldap3.ROUND_ROBIN, active=True)

477

478

conn = ldap3.Connection(server_pool, 'cn=user,dc=example,dc=com', 'password', auto_bind=True)

479

```

480

481

### Context Manager Usage

482

483

```python

484

import ldap3

485

486

server = ldap3.Server('ldap.example.com')

487

with ldap3.Connection(server, 'cn=user,dc=example,dc=com', 'password', auto_bind=True) as conn:

488

conn.search('dc=example,dc=com', '(objectClass=person)')

489

# Connection automatically closed when exiting context

490

```

491

492

### SASL Authentication

493

494

```python

495

import ldap3

496

497

server = ldap3.Server('ldap.example.com')

498

conn = ldap3.Connection(server, sasl_mechanism=ldap3.KERBEROS, sasl_credentials=())

499

conn.bind()

500

```

501

502

### Asynchronous Connection

503

504

```python

505

import ldap3

506

507

server = ldap3.Server('ldap.example.com')

508

conn = ldap3.Connection(server, 'cn=user,dc=example,dc=com', 'password',

509

client_strategy=ldap3.ASYNC, auto_bind=True)

510

511

# Operations return immediately, check results later

512

message_id = conn.search('dc=example,dc=com', '(objectClass=person)')

513

result = conn.get_response(message_id)

514

```