Metadata-Version: 2.4
Name: netherframe.discovery.keycloak.keycloak
Version: 0.4.0
Summary: Keycloak resource discovery for Netherframe
Author: Sourabh Cheedella
Author-email: Sourabh Cheedella <cheedella.sourabh@gmail.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.15
Requires-Dist: netherframe-core>=0.13.0,<1.0.0
Requires-Dist: netherframe-generation>=0.5.0,<1.0.0
Requires-Dist: httpx>=0.28.1
Requires-Dist: python-keycloak>=7.1.1
Requires-Python: >=3.15
Project-URL: Homepage, https://netherframe.arsenal.sh
Project-URL: Repository, https://github.com/arsenal-sh/netherframe
Description-Content-Type: text/markdown

# Keycloak Discovery Package for Netherframe

This package provides resource discovery capabilities for Keycloak, enabling automatic import of existing Keycloak resources into Netherframe Infrastructure as Code.

## Installation

```bash
pip install netherframe.discovery.keycloak.keycloak
```

## Prerequisites

- Python 3.11+
- A running Keycloak instance
- Admin credentials or client credentials with appropriate permissions
- `python-keycloak` library (automatically installed with this package)

## Codifying a realm

`nf discover codify keycloak` writes typed Netherframe code for a live realm: every object is
imported through the `keycloak/keycloak` provider, so the code reproduces the provider's state,
with references between objects, provider defaults left out and secrets read from environment
variables. See [Codifying a Keycloak Realm](../../docs/guides/codifying-a-keycloak-realm.md).

```bash
export KEYCLOAK_USER=admin KEYCLOAK_PASSWORD=...
nf discover codify keycloak --url http://localhost:8080 --realm demo -o realm_demo.py
```

From Python: `codify_realm(api, provider_client, "demo")` (`netherframe.discovery.keycloak.keycloak`),
with `KeycloakConnection.from_config(config)` for the admin API and a configured provider.
`KeycloakProviderDiscoverer` (entry point `keycloak-provider` in `nf.discoverers`) is the same
discovery as a `ResourceDiscoverer`: its attributes are the provider's state, secrets left out
and named in `arguments_to_supply`.

## Authentication Setup

The Keycloak discoverer supports two authentication methods:

### 1. Username/Password Authentication

```python
config = {
    "server_url": "https://keycloak.example.com",
    "username": "admin",
    "password": "admin-password",
    "realm_name": "master",  # Optional, defaults to "master"
}
```

### 2. Client Credentials Authentication

```python
config = {
    "server_url": "https://keycloak.example.com",
    "client_id": "my-client",
    "client_secret": "client-secret",
    "realm_name": "master",  # Optional, defaults to "master"
}
```

## Basic Usage

```python
from nf.discovery.keycloak.keycloak import KeycloakDiscoverer

# Initialize discoverer
discoverer = KeycloakDiscoverer()

# Configure connection
config = {
    "server_url": "https://keycloak.example.com",
    "username": "admin",
    "password": "admin123",
}

# Discover all resources
resources = discoverer.discover_resources(config)

# Process discovered resources
for resource in resources:
    print(f"Found {resource.resource_type}: {resource.import_id}")
```

## Supported Resources

This discovery package supports all 96 Keycloak resources (100% coverage). The following resources have discovery implementations:

### Currently Implemented Resources

#### Core Resources
- `keycloak_realm` - Keycloak realms
- `keycloak_group` - User groups
- `keycloak_user` - User accounts
- `keycloak_role` - Realm and client roles

#### Client Resources
- `keycloak_openid_client` - OpenID Connect clients
- `keycloak_saml_client` - SAML clients
- `keycloak_openid_client_scope` - Client scopes
- `keycloak_openid_client_default_scopes` - Default client scope assignments
- `keycloak_openid_client_optional_scopes` - Optional client scope assignments

#### Authentication Resources
- `keycloak_authentication_flow` - Authentication flows
- `keycloak_authentication_subflow` - Authentication subflows
- `keycloak_authentication_execution` - Authentication executions
- `keycloak_authentication_execution_config` - Execution configurations
- `keycloak_authentication_bindings` - Flow bindings (browser, registration, etc.)

#### Identity Provider Resources
- `keycloak_oidc_identity_provider` - Generic OIDC identity providers
- `keycloak_saml_identity_provider` - SAML identity providers
- `keycloak_oidc_google_identity_provider` - Google identity provider (special case)

#### Identity Provider Mapper Resources
- `keycloak_attribute_importer_identity_provider_mapper` - Import attributes from IDPs
- `keycloak_attribute_to_role_identity_provider_mapper` - Map IDP attributes to roles
- `keycloak_hardcoded_attribute_identity_provider_mapper` - Add hardcoded attributes
- `keycloak_hardcoded_role_identity_provider_mapper` - Add hardcoded roles
- `keycloak_hardcoded_group_identity_provider_mapper` - Add hardcoded groups
- `keycloak_user_template_importer_identity_provider_mapper` - Template-based username mapping

#### Protocol Mapper Resources - OpenID Connect
- `keycloak_openid_user_attribute_protocol_mapper` - Map user attributes to token claims
- `keycloak_openid_user_property_protocol_mapper` - Map user properties to token claims
- `keycloak_openid_group_membership_protocol_mapper` - Map user groups to token claims
- `keycloak_openid_full_name_protocol_mapper` - Add full name to tokens
- `keycloak_openid_hardcoded_claim_protocol_mapper` - Add hardcoded claims to tokens
- `keycloak_openid_audience_protocol_mapper` - Add audience to tokens
- `keycloak_openid_audience_resolve_protocol_mapper` - Resolve and add audience to tokens
- `keycloak_openid_hardcoded_role_protocol_mapper` - Add hardcoded roles to tokens
- `keycloak_openid_user_realm_role_protocol_mapper` - Map realm roles to token claims
- `keycloak_openid_user_client_role_protocol_mapper` - Map client roles to token claims
- `keycloak_openid_user_session_note_protocol_mapper` - Map session notes to token claims
- `keycloak_openid_script_protocol_mapper` - Script-based token claim mapping

#### Protocol Mapper Resources - SAML
- `keycloak_saml_user_attribute_protocol_mapper` - Map user attributes to SAML assertions
- `keycloak_saml_user_property_protocol_mapper` - Map user properties to SAML assertions
- `keycloak_saml_script_protocol_mapper` - Script-based SAML assertion mapping

#### Protocol Mapper Resources - Generic
- `keycloak_generic_client_protocol_mapper` - Generic protocol mapper for clients
- `keycloak_generic_protocol_mapper` - Generic protocol mapper for client scopes
- `keycloak_generic_client_role_mapper` - Generic role mapper for clients
- `keycloak_generic_role_mapper` - Generic role mapper for client scopes
- `keycloak_hardcoded_attribute_mapper` - Add hardcoded attributes

#### Custom Resources
- `keycloak_custom_user_federation` - Custom user federation providers (non-LDAP)
- `keycloak_custom_identity_provider_mapper` - Custom identity provider mappers

#### Membership and Role Assignment Resources
- `keycloak_default_groups` - Default groups assigned to new users
- `keycloak_default_roles` - Default roles assigned to new users
- `keycloak_group_memberships` - Members of a specific group
- `keycloak_user_groups` - Groups assigned to a specific user
- `keycloak_group_roles` - Roles assigned to a specific group
- `keycloak_user_roles` - Roles assigned to a specific user

#### LDAP Resources
- `keycloak_ldap_user_federation` - LDAP user federation providers
- `keycloak_ldap_user_attribute_mapper` - Map LDAP attributes to user attributes
- `keycloak_ldap_full_name_mapper` - Map full name from LDAP
- `keycloak_ldap_group_mapper` - Map LDAP groups to Keycloak groups
- `keycloak_ldap_role_mapper` - Map LDAP groups to Keycloak roles
- `keycloak_ldap_custom_mapper` - Custom LDAP attribute mappers
- `keycloak_ldap_hardcoded_attribute_mapper` - Add hardcoded attributes from LDAP
- `keycloak_ldap_hardcoded_group_mapper` - Add hardcoded groups from LDAP
- `keycloak_ldap_hardcoded_role_mapper` - Add hardcoded roles from LDAP
- `keycloak_ldap_msad_user_account_control_mapper` - Map Microsoft AD user account control
- `keycloak_ldap_msad_lds_user_account_control_mapper` - Map Microsoft AD LDS user account control

#### Client Authorization Resources
- `keycloak_openid_client_authorization_resource` - Authorization resources
- `keycloak_openid_client_authorization_scope` - Authorization scopes
- `keycloak_openid_client_authorization_permission` - Authorization permissions

#### Client Authorization Policies
- `keycloak_openid_client_group_policy` - Group-based authorization policies
- `keycloak_openid_client_role_policy` - Role-based authorization policies
- `keycloak_openid_client_user_policy` - User-based authorization policies
- `keycloak_openid_client_client_policy` - Client-based authorization policies
- `keycloak_openid_client_time_policy` - Time-based authorization policies
- `keycloak_openid_client_aggregate_policy` - Aggregate authorization policies
- `keycloak_openid_client_js_policy` - JavaScript-based authorization policies
- `keycloak_openid_client_authorization_client_scope_policy` - Client scope-based authorization policies

### Complete Resource Coverage

All 96 Keycloak resources are now supported with discovery implementations! This includes:

- **Service Account Resources**: Service account roles (both realm and client roles)
- **Permissions Resources**: Group, user, client, and identity provider token exchange permissions
- **Realm Configuration**: Events, user profiles, keystores, localization, and client policies
- **Organization Support**: Full organization discovery
- **Keystore Resources**: All 6 types of keystores (AES, ECDSA, HMAC, Java Keystore, RSA, RSA Generated)
- **SAML Resources**: SAML client scopes and default scope assignments

To see all supported resource types, run:
```python
discoverer = KeycloakDiscoverer()
print(discoverer.get_supported_resource_types())
```

## Configuration Options

### Connection Settings

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `server_url` | string | Yes | Keycloak server URL |
| `username` | string | Conditional | Admin username (required if not using client credentials) |
| `password` | string | Conditional | Admin password (required with username) |
| `client_id` | string | No | Client ID for client credentials auth (default: "admin-cli") |
| `client_secret` | string | Conditional | Client secret (required with client_id) |
| `realm_name` | string | No | Initial realm name (default: "master") |
| `verify_ssl` | boolean | No | Verify SSL certificates (default: True) |

### Discovery Settings

| Option | Type | Description |
|--------|------|-------------|
| `resource_types` | list | Specific resource types to discover (default: all) |
| `max_users` | int | Maximum number of users to discover (default: 100) |

## Filters

The discoverer supports various filters to limit discovery scope:

```python
filters = {
    "realm_names": ["master", "production"],  # Only discover specific realms
    "skip_builtin": True,  # Skip built-in authentication flows
    "skip_internal": True,  # Skip internal clients
    "skip_composite": True,  # Skip composite roles
    "max_users": 50,  # Limit user discovery
}

resources = discoverer.discover_resources(config, filters)
```

## Error Handling

The discoverer is designed to be resilient:
- Continues discovery even if some resources fail
- Logs warnings for failed resource types
- Returns all successfully discovered resources

## Import ID Formats

Different resources use different import ID formats:

| Resource Type | Import ID Format | Example |
|---------------|------------------|---------|
| Realm | `{realm_name}` | `master` |
| Group | `{realm}/{group_id}` | `master/123e4567-e89b` |
| User | `{realm}/{user_id}` | `master/456f7890-a12b` |
| Role | `{realm}/{role_id}` | `master/789g0123-c34d` |
| Client | `{realm}/{client_id}` | `master/012h3456-e56f` |

## Performance Considerations

1. **User Discovery**: Limited by default to 100 users per realm. Adjust `max_users` in filters for larger deployments.

2. **Hierarchical Discovery**: Discovers realms first, then realm-scoped resources for efficiency.

3. **Batch Operations**: Uses list operations to minimize API calls.

4. **Selective Discovery**: Use `resource_types` config to discover only needed resources.

## Example: Selective Discovery

```python
# Discover only realms and clients
config = {"server_url": "https://keycloak.example.com", "username": "admin", "password": "admin123", "resource_types": ["keycloak_realm", "keycloak_openid_client"]}

resources = discoverer.discover_resources(config)
```

## Troubleshooting

### ImportError: python-keycloak is required

Install the required library:
```bash
pip install python-keycloak
```

### Connection Errors

Verify:
- Keycloak server is accessible
- Credentials are correct
- SSL certificates are valid (or set `verify_ssl: false` for testing)

### Permission Errors

Ensure your user/client has appropriate permissions:
- For full discovery: Admin role in master realm
- For realm-specific discovery: Manage permissions in target realms

## Known Limitations

1. **Full Coverage**: All 96 Keycloak resources are now discoverable (100% coverage)
2. **User Discovery**: Limited by default to prevent overwhelming large deployments
3. **Permissions**: Some resources may require specific permissions to discover
4. **Performance**: Discovery time increases with the number of realms and resources
5. **Organization Support**: Organizations are discovered if supported by your Keycloak version

## Contributing

To add support for new resources or improve existing discovery:
1. Update the `get_supported_resource_types()` method
2. Add discovery method for the new resource type
3. Update tests and documentation
4. Run the coverage analysis script to ensure 100% coverage