oidcauthlib 3.0.30__tar.gz → 3.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. {oidcauthlib-3.0.30/oidcauthlib.egg-info → oidcauthlib-3.1.0}/PKG-INFO +52 -1
  2. oidcauthlib-3.1.0/README.md +94 -0
  3. oidcauthlib-3.1.0/VERSION +1 -0
  4. oidcauthlib-3.1.0/oidcauthlib/authorization/__init__.py +43 -0
  5. oidcauthlib-3.1.0/oidcauthlib/authorization/admin_access.py +122 -0
  6. oidcauthlib-3.1.0/oidcauthlib/authorization/client_keys.py +97 -0
  7. oidcauthlib-3.1.0/oidcauthlib/authorization/client_slugs.py +105 -0
  8. oidcauthlib-3.1.0/oidcauthlib/authorization/reader_configuration.py +70 -0
  9. oidcauthlib-3.1.0/oidcauthlib/authorization/scopes.py +30 -0
  10. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0/oidcauthlib.egg-info}/PKG-INFO +52 -1
  11. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib.egg-info/SOURCES.txt +6 -0
  12. oidcauthlib-3.0.30/README.md +0 -43
  13. oidcauthlib-3.0.30/VERSION +0 -1
  14. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/LICENSE +0 -0
  15. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/MANIFEST.in +0 -0
  16. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/__init__.py +0 -0
  17. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/__init__.py +0 -0
  18. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/auth_helper.py +0 -0
  19. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/auth_manager.py +0 -0
  20. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/cache/__init__.py +0 -0
  21. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/cache/oauth_cache.py +0 -0
  22. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/cache/oauth_memory_cache.py +0 -0
  23. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/cache/oauth_mongo_cache.py +0 -0
  24. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/config/__init__.py +0 -0
  25. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/config/auth_config.py +0 -0
  26. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/config/auth_config_reader.py +0 -0
  27. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/dcr/__init__.py +0 -0
  28. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/dcr/dcr_client.py +0 -0
  29. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/dcr/dcr_manager.py +0 -0
  30. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/dcr/dcr_registration.py +0 -0
  31. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/exceptions/__init__.py +0 -0
  32. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/exceptions/authorization_bearer_token_expired_exception.py +0 -0
  33. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/exceptions/authorization_bearer_token_invalid_exception.py +0 -0
  34. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/exceptions/authorization_bearer_token_missing_exception.py +0 -0
  35. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/exceptions/authorization_needed_exception.py +0 -0
  36. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/fastapi_auth_manager.py +0 -0
  37. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/middleware/__init__.py +0 -0
  38. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/middleware/request_scope_middleware.py +0 -0
  39. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/middleware/token_reader_middleware.py +0 -0
  40. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/models/__init__.py +0 -0
  41. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/models/auth.py +0 -0
  42. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/models/base_db_model.py +0 -0
  43. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/models/cache_item.py +0 -0
  44. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/models/client_key_set.py +0 -0
  45. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/models/token.py +0 -0
  46. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/repository/__init__.py +0 -0
  47. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/repository/base_repository.py +0 -0
  48. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/repository/memory/__init__.py +0 -0
  49. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/repository/memory/memory_repository.py +0 -0
  50. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/repository/mongo/__init__.py +0 -0
  51. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/repository/mongo/mongo_repository.py +0 -0
  52. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/repository/repository_factory.py +0 -0
  53. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/routers/__init__.py +0 -0
  54. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/routers/auth_router.py +0 -0
  55. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/token_reader.py +0 -0
  56. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/userinfo/__init__.py +0 -0
  57. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/userinfo/oidc_userinfo_manager.py +0 -0
  58. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/well_known_configuration/__init__.py +0 -0
  59. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/well_known_configuration/auth_server_metadata.py +0 -0
  60. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/well_known_configuration/auth_server_metadata_discovery.py +0 -0
  61. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/well_known_configuration/well_known_configuration_cache.py +0 -0
  62. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/well_known_configuration/well_known_configuration_cache_result.py +0 -0
  63. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/auth/well_known_configuration/well_known_configuration_manager.py +0 -0
  64. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/cache_gate/__init__.py +0 -0
  65. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/cache_gate/advisory_lock.py +0 -0
  66. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/cache_gate/version_gate.py +0 -0
  67. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/container/__init__.py +0 -0
  68. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/container/oidc_authlib_container_factory.py +0 -0
  69. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/open_telemetry/__init__.py +0 -0
  70. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/open_telemetry/attribute_names.py +0 -0
  71. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/open_telemetry/configurator.py +0 -0
  72. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/open_telemetry/filtering_sampler.py +0 -0
  73. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/open_telemetry/filtering_span_exporter.py +0 -0
  74. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/open_telemetry/filtering_span_processor.py +0 -0
  75. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/open_telemetry/otel_setup.py +0 -0
  76. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/open_telemetry/span_names.py +0 -0
  77. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/py.typed +0 -0
  78. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/storage/__init__.py +0 -0
  79. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/storage/cache_to_collection_mapper.py +0 -0
  80. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/storage/memory_storage_factory.py +0 -0
  81. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/storage/mongo_gridfs_db.py +0 -0
  82. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/storage/mongo_gridfs_exception.py +0 -0
  83. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/storage/mongo_storage_factory.py +0 -0
  84. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/storage/storage_factory.py +0 -0
  85. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/storage/storage_factory_creator.py +0 -0
  86. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/utilities/__init__.py +0 -0
  87. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/utilities/cached.py +0 -0
  88. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/utilities/environment/__init__.py +0 -0
  89. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/utilities/environment/abstract_environment_variables.py +0 -0
  90. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/utilities/environment/oidc_environment_variables.py +0 -0
  91. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/utilities/logger/__init__.py +0 -0
  92. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/utilities/logger/log_levels.py +0 -0
  93. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/utilities/logger/logging_response.py +0 -0
  94. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/utilities/logger/logging_transport.py +0 -0
  95. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/utilities/mongo_url_utils.py +0 -0
  96. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib/utilities/url_validator.py +0 -0
  97. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib.egg-info/dependency_links.txt +0 -0
  98. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib.egg-info/requires.txt +0 -0
  99. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/oidcauthlib.egg-info/top_level.txt +0 -0
  100. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/pyproject.toml +0 -0
  101. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/setup.cfg +0 -0
  102. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/tests/test_mongo_url_utils.py +0 -0
  103. {oidcauthlib-3.0.30 → oidcauthlib-3.1.0}/tests/test_simple.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: oidcauthlib
3
- Version: 3.0.30
3
+ Version: 3.1.0
4
4
  Summary: oidcauthlib
5
5
  Author-email: Imran Qureshi <imran.qureshi@bwell.com>
6
6
  License: Apache-2.0
@@ -69,3 +69,54 @@ scopes = await manager.get_scopes_from_user_info_async(access_token=token)
69
69
  malformed entry is logged and treated as a miss, and the refetched scopes overwrite the bad entry. A
70
70
  userinfo HTTP error, a missing provider or a mismatched subject is raised, so each service decides whether
71
71
  to fail closed or degrade.
72
+
73
+ ## Administrator and tenant-reader tiers (`oidcauthlib.authorization`)
74
+
75
+ Pure helpers that turn a caller's merged scopes (for example the result of `OidcUserInfoManager`) into a
76
+ tier: `admin` (unrestricted), `reader` (limited to the client keys its `access/<slug>.*` scopes select), or
77
+ denied. The subpackage reads no environment variable, does no I/O and imports nothing else from
78
+ `oidcauthlib`; the caller verifies the token, looks up the user and passes the configuration in.
79
+
80
+ ```python
81
+ from oidcauthlib.authorization import (
82
+ ClientSlugResolver,
83
+ parse_client_keys_lenient,
84
+ resolve_admin_access,
85
+ validate_reader_configuration,
86
+ )
87
+
88
+ RAW_CLIENTS = "One=key-1,Two=key-2" # the setting that holds the client-key mapping
89
+
90
+ # At startup: refuse an unsafe configuration (a no-op when no reader scopes are set).
91
+ validate_reader_configuration(
92
+ reader_scopes=["example/reader"],
93
+ admin_scopes=["example/admin"],
94
+ client_keys_raw=RAW_CLIENTS,
95
+ )
96
+
97
+ clients = ClientSlugResolver.from_client_keys(clients=parse_client_keys_lenient(raw=RAW_CLIENTS))
98
+ access = resolve_admin_access(
99
+ scopes=["example/reader", "access/one.*"],
100
+ admin_scopes=["example/admin"],
101
+ reader_scopes=["example/reader"],
102
+ clients=clients,
103
+ allow_all_tenants=False,
104
+ )
105
+ # access.tier is AdminTier.READER and access.allowed_client_keys == frozenset({"key-1"})
106
+ ```
107
+
108
+ - **Order:** any `patient/` scope (trimmed, case-insensitive) denies first; then holding every admin scope
109
+ gives `admin`; then every reader scope plus at least one `access/<slug>.*` that selects a client gives
110
+ `reader`; anything else is denied with a `DenialReason`. An empty admin or reader requirement admits nobody.
111
+ - **Slugs:** `access/<slug>.*` selects the client whose name, stripped and casefolded, equals the slug. Two
112
+ names that casefold alike make the slug ambiguous and it selects nothing. The suffix must be exactly `.*`.
113
+ `access/*.*` selects every client only when `allow_all_tenants=True`.
114
+ - **No default for "all tenants":** `allowed_client_keys` is `None` only for `admin`. A reader always has a
115
+ non-empty set and a denied caller always has `frozenset()`, so a denial can never be read as unrestricted.
116
+ `AdminAccess` enforces this when it is constructed.
117
+ - **Client-key mapping:** a `name -> key` map given as a JSON object or `One=key-1,Two=key-2`.
118
+ `parse_client_keys_lenient` keeps the permissive behavior (a malformed JSON object falls back to comma
119
+ parsing, an entry without `=` is dropped); `parse_client_keys_strict` refuses both, and refuses blank or
120
+ repeated names. Error messages name the rule, never a name or key.
121
+ - **Eligibility:** `from_client_keys(..., is_eligible=...)` takes a `(name, key) -> bool` strategy for
122
+ callers that exclude some clients; an excluded client is in no view and takes no part in ambiguity.
@@ -0,0 +1,94 @@
1
+ # oidcauthlib
2
+
3
+ ## OIDC userinfo scopes (`OidcUserInfoManager`)
4
+
5
+ Some providers (e.g. Okta employee access tokens) only carry `openid profile email groups` in the JWT;
6
+ the scopes that authorize a caller appear only on the OIDC userinfo response.
7
+ `oidcauthlib.auth.userinfo.oidc_userinfo_manager.OidcUserInfoManager` resolves a token's effective
8
+ scopes from the token's own claims plus the userinfo endpoint, and caches the userinfo-derived scopes in
9
+ a key-value store.
10
+
11
+ ```python
12
+ manager = OidcUserInfoManager(
13
+ auth_config_reader=auth_config_reader,
14
+ well_known_configuration_manager=well_known_configuration_manager,
15
+ store=store, # py-key-value-aio store; yours, not shared with other services
16
+ cache_collection="oidc-user-info-cache",
17
+ cache_ttl_seconds=86400,
18
+ fetch_timeout_seconds=30,
19
+ scope_claims=["custom:scope"], # optional extra claims holding scopes
20
+ group_claims=["groups"], # optional claims holding group names, used whole as scopes
21
+ scope_remove_prefixes=["fhir/prod/"],
22
+ )
23
+ scopes = await manager.get_scopes_from_user_info_async(access_token=token)
24
+ ```
25
+
26
+ - **Scope derivation** follows fhir-server-ui's `jwtParser`: the `scope` claim (plus `scp`), then
27
+ `scope_claims`, then `group_claims` (each value taken whole). Commas separate like spaces, results are
28
+ de-duplicated, and `scope_remove_prefixes` are stripped (first match wins). Nothing beyond `scope`/`scp`
29
+ is read unless configured.
30
+ - **Provider** is matched to the token's `iss`: an exact `issuer`, else a `well_known_uri` on the same scheme,
31
+ host and port whose path segments start with the issuer's. Only a token with no `iss` at all is matched by
32
+ its client id. A token matching no provider raises `ValueError`; it is never sent to another provider.
33
+ - **Subject check:** for a token that has a `sub`, the userinfo response must carry the same `sub`
34
+ (OIDC Core 5.3.2); a missing or different one raises `ValueError` and nothing is cached.
35
+ - **Cache** key is `oidc-userinfo-scopes:<issuer>:<client_id>:<sub>|v1` with each segment percent-encoded
36
+ (so values containing `:` cannot collide, and two providers never share an entry); only the
37
+ userinfo-derived scopes are stored, never the userinfo response. The token's own scopes are re-derived on every call. A token without
38
+ `sub` or without an issuer, or an empty scope list, is not cached. Changes to a user's entitlements are visible after at most
39
+ `cache_ttl_seconds`.
40
+ - **Failures:** the cache never fails a lookup. A write failure is logged and swallowed; a read failure or a
41
+ malformed entry is logged and treated as a miss, and the refetched scopes overwrite the bad entry. A
42
+ userinfo HTTP error, a missing provider or a mismatched subject is raised, so each service decides whether
43
+ to fail closed or degrade.
44
+
45
+ ## Administrator and tenant-reader tiers (`oidcauthlib.authorization`)
46
+
47
+ Pure helpers that turn a caller's merged scopes (for example the result of `OidcUserInfoManager`) into a
48
+ tier: `admin` (unrestricted), `reader` (limited to the client keys its `access/<slug>.*` scopes select), or
49
+ denied. The subpackage reads no environment variable, does no I/O and imports nothing else from
50
+ `oidcauthlib`; the caller verifies the token, looks up the user and passes the configuration in.
51
+
52
+ ```python
53
+ from oidcauthlib.authorization import (
54
+ ClientSlugResolver,
55
+ parse_client_keys_lenient,
56
+ resolve_admin_access,
57
+ validate_reader_configuration,
58
+ )
59
+
60
+ RAW_CLIENTS = "One=key-1,Two=key-2" # the setting that holds the client-key mapping
61
+
62
+ # At startup: refuse an unsafe configuration (a no-op when no reader scopes are set).
63
+ validate_reader_configuration(
64
+ reader_scopes=["example/reader"],
65
+ admin_scopes=["example/admin"],
66
+ client_keys_raw=RAW_CLIENTS,
67
+ )
68
+
69
+ clients = ClientSlugResolver.from_client_keys(clients=parse_client_keys_lenient(raw=RAW_CLIENTS))
70
+ access = resolve_admin_access(
71
+ scopes=["example/reader", "access/one.*"],
72
+ admin_scopes=["example/admin"],
73
+ reader_scopes=["example/reader"],
74
+ clients=clients,
75
+ allow_all_tenants=False,
76
+ )
77
+ # access.tier is AdminTier.READER and access.allowed_client_keys == frozenset({"key-1"})
78
+ ```
79
+
80
+ - **Order:** any `patient/` scope (trimmed, case-insensitive) denies first; then holding every admin scope
81
+ gives `admin`; then every reader scope plus at least one `access/<slug>.*` that selects a client gives
82
+ `reader`; anything else is denied with a `DenialReason`. An empty admin or reader requirement admits nobody.
83
+ - **Slugs:** `access/<slug>.*` selects the client whose name, stripped and casefolded, equals the slug. Two
84
+ names that casefold alike make the slug ambiguous and it selects nothing. The suffix must be exactly `.*`.
85
+ `access/*.*` selects every client only when `allow_all_tenants=True`.
86
+ - **No default for "all tenants":** `allowed_client_keys` is `None` only for `admin`. A reader always has a
87
+ non-empty set and a denied caller always has `frozenset()`, so a denial can never be read as unrestricted.
88
+ `AdminAccess` enforces this when it is constructed.
89
+ - **Client-key mapping:** a `name -> key` map given as a JSON object or `One=key-1,Two=key-2`.
90
+ `parse_client_keys_lenient` keeps the permissive behavior (a malformed JSON object falls back to comma
91
+ parsing, an entry without `=` is dropped); `parse_client_keys_strict` refuses both, and refuses blank or
92
+ repeated names. Error messages name the rule, never a name or key.
93
+ - **Eligibility:** `from_client_keys(..., is_eligible=...)` takes a `(name, key) -> bool` strategy for
94
+ callers that exclude some clients; an excluded client is in no view and takes no part in ambiguity.
@@ -0,0 +1 @@
1
+ 3.1.0
@@ -0,0 +1,43 @@
1
+ """Pure authorization helpers: administrator and tenant-reader tiers from OAuth scopes.
2
+
3
+ Everything here is a pure function of the values passed in. The package reads no
4
+ environment variable, performs no I/O and imports nothing else from ``oidcauthlib``,
5
+ so callers keep control of token verification, user lookup and configuration.
6
+ """
7
+
8
+ from oidcauthlib.authorization.admin_access import (
9
+ AdminAccess,
10
+ AdminTier,
11
+ DenialReason,
12
+ resolve_admin_access,
13
+ )
14
+ from oidcauthlib.authorization.client_keys import (
15
+ ClientKeysFormatError,
16
+ parse_client_keys_lenient,
17
+ parse_client_keys_strict,
18
+ )
19
+ from oidcauthlib.authorization.client_slugs import (
20
+ ClientSlugResolver,
21
+ slug_from_access_scope,
22
+ )
23
+ from oidcauthlib.authorization.reader_configuration import (
24
+ ReaderConfigurationError,
25
+ validate_reader_configuration,
26
+ )
27
+ from oidcauthlib.authorization.scopes import has_admin_scopes, has_patient_scope
28
+
29
+ __all__ = [
30
+ "AdminAccess",
31
+ "AdminTier",
32
+ "ClientKeysFormatError",
33
+ "ClientSlugResolver",
34
+ "DenialReason",
35
+ "ReaderConfigurationError",
36
+ "has_admin_scopes",
37
+ "has_patient_scope",
38
+ "parse_client_keys_lenient",
39
+ "parse_client_keys_strict",
40
+ "resolve_admin_access",
41
+ "slug_from_access_scope",
42
+ "validate_reader_configuration",
43
+ ]
@@ -0,0 +1,122 @@
1
+ """Which tier a caller's merged scopes grant: administrator, tenant reader, or denied.
2
+
3
+ Pure: scopes in, ``AdminAccess`` out. No web framework, environment or network.
4
+
5
+ Order of the rules:
6
+
7
+ 1. any ``patient/`` scope denies, even with an administrator or reader scope;
8
+ 2. every administrator scope held: ``ADMIN``, unrestricted;
9
+ 3. every reader scope held plus at least one ``access/<slug>.*`` whose slug
10
+ selects a client: ``READER``, limited to those clients' keys. ``access/*.*``
11
+ is honored only when ``allow_all_tenants`` is set, and then means every
12
+ client in the resolver (a set, so a record outside it stays administrator-only);
13
+ 4. anything else is denied, with the reason that names the missing piece.
14
+
15
+ Scope matching is exact on the required scopes, and ``access/*.*`` alone never
16
+ grants the reader tier.
17
+ """
18
+
19
+ from collections.abc import Iterable, Sequence
20
+ from dataclasses import dataclass
21
+ from enum import StrEnum
22
+
23
+ from oidcauthlib.authorization.client_slugs import (
24
+ WILDCARD_SLUG,
25
+ ClientSlugResolver,
26
+ slug_from_access_scope,
27
+ )
28
+ from oidcauthlib.authorization.scopes import has_admin_scopes, has_patient_scope
29
+
30
+
31
+ class AdminTier(StrEnum):
32
+ ADMIN = "admin"
33
+ READER = "reader"
34
+
35
+
36
+ class DenialReason(StrEnum):
37
+ """Why a caller was denied; also usable as a metric label."""
38
+
39
+ PATIENT_SCOPE = "patient_scope"
40
+ NOT_A_READER = "not_a_reader"
41
+ NO_ACCESS_SCOPE = "no_access_scope"
42
+ UNMAPPED_ACCESS_SCOPE = "unmapped_access_scope"
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class AdminAccess:
47
+ """The outcome of a tier decision.
48
+
49
+ ``tier`` is ``None`` when the caller is denied, with ``denial_reason`` set.
50
+ ``allowed_client_keys`` has three meanings, enforced in ``__post_init__``:
51
+
52
+ * ``None``: unrestricted. Only the ``ADMIN`` tier carries it.
53
+ * a non-empty set: the client keys a ``READER`` may read.
54
+ * an empty set: a denied caller. A denied caller never carries ``None``, so
55
+ no code path can read a denial as "all tenants".
56
+
57
+ Prefer the ``admin``, ``reader`` and ``denied`` constructors.
58
+ """
59
+
60
+ tier: AdminTier | None
61
+ allowed_client_keys: frozenset[str] | None
62
+ denial_reason: DenialReason | None
63
+
64
+ def __post_init__(self) -> None:
65
+ if self.tier is AdminTier.READER and not self.allowed_client_keys:
66
+ raise ValueError("a reader needs a non-empty set of client keys it may read")
67
+ if self.tier is AdminTier.ADMIN and self.allowed_client_keys is not None:
68
+ raise ValueError("the admin tier is unrestricted: allowed_client_keys must be None")
69
+ if self.tier is None:
70
+ if self.denial_reason is None:
71
+ raise ValueError("a denied caller needs a denial reason")
72
+ if self.allowed_client_keys != frozenset():
73
+ raise ValueError("a denied caller carries an empty set of client keys, never None")
74
+
75
+ @classmethod
76
+ def admin(cls) -> "AdminAccess":
77
+ return cls(tier=AdminTier.ADMIN, allowed_client_keys=None, denial_reason=None)
78
+
79
+ @classmethod
80
+ def reader(cls, *, allowed_client_keys: frozenset[str]) -> "AdminAccess":
81
+ return cls(
82
+ tier=AdminTier.READER,
83
+ allowed_client_keys=allowed_client_keys,
84
+ denial_reason=None,
85
+ )
86
+
87
+ @classmethod
88
+ def denied(cls, *, reason: DenialReason) -> "AdminAccess":
89
+ return cls(tier=None, allowed_client_keys=frozenset(), denial_reason=reason)
90
+
91
+
92
+ def resolve_admin_access(
93
+ *,
94
+ scopes: Iterable[str],
95
+ admin_scopes: Sequence[str],
96
+ reader_scopes: Sequence[str],
97
+ clients: ClientSlugResolver,
98
+ allow_all_tenants: bool,
99
+ ) -> AdminAccess:
100
+ """The tier ``scopes`` (the merged token and userinfo scopes) grant.
101
+
102
+ ``admin_scopes`` and ``reader_scopes`` are all-of requirements; an empty one
103
+ admits nobody. ``allow_all_tenants`` lets ``access/*.*`` select every client
104
+ in ``clients``. Never raises.
105
+ """
106
+ held = set(scopes)
107
+ if has_patient_scope(scopes=held):
108
+ return AdminAccess.denied(reason=DenialReason.PATIENT_SCOPE)
109
+ if has_admin_scopes(scopes=held, required_scopes=admin_scopes):
110
+ return AdminAccess.admin()
111
+ # An empty requirement would admit everyone (``issubset`` of the empty set).
112
+ if not reader_scopes or not set(reader_scopes).issubset(held):
113
+ return AdminAccess.denied(reason=DenialReason.NOT_A_READER)
114
+ slugs = {slug for scope in held if (slug := slug_from_access_scope(scope=scope)) is not None}
115
+ if not slugs:
116
+ return AdminAccess.denied(reason=DenialReason.NO_ACCESS_SCOPE)
117
+ if WILDCARD_SLUG in slugs and allow_all_tenants and clients.all_keys:
118
+ return AdminAccess.reader(allowed_client_keys=clients.all_keys)
119
+ keys = frozenset(key for slug in slugs - {WILDCARD_SLUG} for key in clients.keys_for(slug=slug))
120
+ if not keys:
121
+ return AdminAccess.denied(reason=DenialReason.UNMAPPED_ACCESS_SCOPE)
122
+ return AdminAccess.reader(allowed_client_keys=keys)
@@ -0,0 +1,97 @@
1
+ """Parsers for a client-key mapping: a ``name -> key`` map held in one setting.
2
+
3
+ The raw value is either a JSON object (``{"One": "key-1"}``) or a comma-separated
4
+ list (``One=key-1,Two=key-2``). Two parsers read it:
5
+
6
+ * ``parse_client_keys_lenient`` keeps the historical behavior of services that
7
+ read this setting: a malformed JSON object falls back to comma parsing and an
8
+ entry without ``=`` is dropped silently.
9
+ * ``parse_client_keys_strict`` is for startup validation: it refuses anything the
10
+ lenient parser would silently repair or drop.
11
+
12
+ Error messages name the rule that failed, never a client name or a key.
13
+ """
14
+
15
+ import json
16
+ from typing import Any
17
+
18
+
19
+ class ClientKeysFormatError(ValueError):
20
+ """The raw client-key mapping is malformed."""
21
+
22
+
23
+ def parse_client_keys_lenient(*, raw: str) -> dict[str, str]:
24
+ """Parse the mapping, repairing or dropping what it cannot read.
25
+
26
+ An empty value gives ``{}``. A JSON object parses as is; invalid JSON falls
27
+ back to comma parsing. In the comma form, an entry without ``=`` is dropped.
28
+ """
29
+ if not raw:
30
+ return {}
31
+ if raw.strip().startswith("{"):
32
+ try:
33
+ return dict(json.loads(raw))
34
+ except (json.JSONDecodeError, TypeError):
35
+ pass
36
+ clients: dict[str, str] = {}
37
+ for entry in raw.split(","):
38
+ entry = entry.strip()
39
+ if "=" in entry:
40
+ name, value = entry.split("=", 1)
41
+ clients[name.strip()] = value.strip()
42
+ return clients
43
+
44
+
45
+ def parse_client_keys_strict(*, raw: str) -> dict[str, str]:
46
+ """Parse the mapping and refuse anything the lenient parser would repair.
47
+
48
+ Raises:
49
+ ClientKeysFormatError: invalid JSON (no fall-back to comma parsing), a
50
+ JSON value that is not an object of strings, duplicate JSON keys, a
51
+ comma entry without ``=``, a blank name or key, or a name repeated
52
+ after stripping and casefolding (exact repeats included).
53
+ """
54
+ text = raw.strip()
55
+ if not text:
56
+ return {}
57
+ pairs = _json_pairs(text) if text.startswith("{") else _comma_pairs(text)
58
+ clients: dict[str, str] = {}
59
+ seen: set[str] = set()
60
+ for position, (name, key) in enumerate(pairs, start=1):
61
+ clean_name = name.strip()
62
+ clean_key = key.strip()
63
+ if not clean_name or not clean_key:
64
+ raise ClientKeysFormatError(f"entry {position} has a blank name or key")
65
+ folded = clean_name.casefold()
66
+ if folded in seen:
67
+ raise ClientKeysFormatError(f"entry {position} repeats a name after stripping and ignoring case")
68
+ seen.add(folded)
69
+ clients[clean_name] = clean_key
70
+ return clients
71
+
72
+
73
+ def _json_pairs(text: str) -> list[tuple[str, str]]:
74
+ try:
75
+ parsed: Any = json.loads(text, object_pairs_hook=lambda pairs: pairs)
76
+ except json.JSONDecodeError as exc:
77
+ raise ClientKeysFormatError("the value is not valid JSON") from exc
78
+ if not isinstance(parsed, list):
79
+ raise ClientKeysFormatError("the JSON value is not an object")
80
+ pairs: list[tuple[str, str]] = []
81
+ for position, (name, key) in enumerate(parsed, start=1):
82
+ if not isinstance(key, str):
83
+ raise ClientKeysFormatError(f"entry {position} has a value that is not a string")
84
+ pairs.append((name, key))
85
+ return pairs
86
+
87
+
88
+ def _comma_pairs(text: str) -> list[tuple[str, str]]:
89
+ if text.startswith("["):
90
+ raise ClientKeysFormatError("the JSON value is not an object")
91
+ pairs: list[tuple[str, str]] = []
92
+ for position, entry in enumerate(text.split(","), start=1):
93
+ if "=" not in entry:
94
+ raise ClientKeysFormatError(f"entry {position} has no '='")
95
+ name, key = entry.split("=", 1)
96
+ pairs.append((name, key))
97
+ return pairs
@@ -0,0 +1,105 @@
1
+ """Which client keys an ``access/<slug>.*`` scope selects.
2
+
3
+ A slug is the text between ``access/`` and the trailing ``.*`` of the scope. It
4
+ selects the client whose name, stripped and casefolded, equals the stripped,
5
+ casefolded slug. One slug selects one key. A slug that matches no name is
6
+ unmapped; two names that casefold alike make the slug ambiguous, and an
7
+ ambiguous slug selects nothing (logged by slug only, never by key). The ``*``
8
+ slug is the wildcard and never selects a single key.
9
+ """
10
+
11
+ import logging
12
+ from collections.abc import Callable, Mapping
13
+ from dataclasses import dataclass, field
14
+ from types import MappingProxyType
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ ACCESS_SCOPE_PREFIX = "access/"
19
+ ACCESS_SCOPE_SUFFIX = ".*"
20
+ # ``access/*.*``: every client in the mapping, honored only when a caller opts in.
21
+ WILDCARD_SLUG = "*"
22
+
23
+
24
+ def normalize_slug(*, slug: str) -> str:
25
+ """Strip and casefold a slug or a client name so they compare equal."""
26
+ return slug.strip().casefold()
27
+
28
+
29
+ def slug_from_access_scope(*, scope: str) -> str | None:
30
+ """The slug of an ``access/<slug>.*`` scope, normalized; ``None`` for any other scope.
31
+
32
+ ``access/tenant.*`` gives ``tenant`` and ``access/*.*`` gives ``*``. The suffix
33
+ must be exactly ``.*``: ``access/demo.read``, ``access/*.read``, ``access/demo``
34
+ and an empty slug (``access/.*``) all give ``None``.
35
+ """
36
+ normalized = scope.strip().casefold()
37
+ if not normalized.startswith(ACCESS_SCOPE_PREFIX):
38
+ return None
39
+ if not normalized.endswith(ACCESS_SCOPE_SUFFIX):
40
+ return None
41
+ body = normalized[len(ACCESS_SCOPE_PREFIX) :]
42
+ slug = body[: -len(ACCESS_SCOPE_SUFFIX)].strip()
43
+ return slug or None
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class ClientSlugResolver:
48
+ """Slug to its one client key, and every eligible client key."""
49
+
50
+ keys_by_slug: Mapping[str, str] = field(default_factory=lambda: MappingProxyType({}))
51
+ all_keys: frozenset[str] = frozenset()
52
+
53
+ @classmethod
54
+ def from_client_keys(
55
+ cls,
56
+ *,
57
+ clients: Mapping[str, str],
58
+ is_eligible: Callable[[str, str], bool] | None = None,
59
+ ) -> "ClientSlugResolver":
60
+ """Build the resolver from a ``name -> key`` map.
61
+
62
+ Args:
63
+ clients: the client-key mapping. Entries with a blank name or key are
64
+ skipped.
65
+ is_eligible: optional strategy ``(name, key) -> bool``. A client it
66
+ rejects is in neither ``keys_by_slug`` nor ``all_keys``, and does
67
+ not take part in ambiguity checks.
68
+ """
69
+ keys_by_slug_candidates: dict[str, list[str]] = {}
70
+ for name, key in clients.items():
71
+ slug = normalize_slug(slug=str(name))
72
+ clean_key = str(key).strip()
73
+ if not slug or not clean_key:
74
+ continue
75
+ if is_eligible is not None and not is_eligible(str(name), clean_key):
76
+ continue
77
+ keys_by_slug_candidates.setdefault(slug, []).append(clean_key)
78
+ keys_by_slug: dict[str, str] = {}
79
+ for slug, keys in keys_by_slug_candidates.items():
80
+ if slug == WILDCARD_SLUG:
81
+ continue
82
+ if len(keys) > 1:
83
+ logger.warning(
84
+ "Client names that casefold to %s are ambiguous; the access slug selects no client",
85
+ slug,
86
+ )
87
+ continue
88
+ keys_by_slug[slug] = keys[0]
89
+ return cls(
90
+ keys_by_slug=MappingProxyType(keys_by_slug),
91
+ all_keys=frozenset(key for keys in keys_by_slug_candidates.values() for key in keys),
92
+ )
93
+
94
+ def keys_for(self, *, slug: str) -> frozenset[str]:
95
+ """The one key ``slug`` selects, or an empty set when it is unmapped or ambiguous."""
96
+ key = self.keys_by_slug.get(normalize_slug(slug=slug))
97
+ return frozenset() if key is None else frozenset({key})
98
+
99
+ def slugs_by_key(self, *, keys: frozenset[str]) -> Mapping[str, str]:
100
+ """Each of ``keys`` that has an unambiguous slug, with that slug.
101
+
102
+ The slug is a bounded label that is safe to use in metrics and audit
103
+ records where the key itself must not appear.
104
+ """
105
+ return MappingProxyType({key: slug for slug, key in self.keys_by_slug.items() if key in keys})
@@ -0,0 +1,70 @@
1
+ """Startup validation of the reader-tier configuration.
2
+
3
+ When reader scopes are configured, the configuration must be one the resolver can
4
+ apply safely. Every refusal names the rule that failed, never a client name or key.
5
+ """
6
+
7
+ from collections.abc import Sequence
8
+
9
+ from oidcauthlib.authorization.client_keys import (
10
+ ClientKeysFormatError,
11
+ parse_client_keys_strict,
12
+ )
13
+ from oidcauthlib.authorization.client_slugs import ACCESS_SCOPE_PREFIX, WILDCARD_SLUG
14
+ from oidcauthlib.authorization.scopes import PATIENT_SCOPE_PREFIX
15
+
16
+ # Scopes every token carries; as a reader requirement they would admit everyone.
17
+ GENERIC_SCOPES = frozenset({"openid", "profile", "email", "groups"})
18
+
19
+
20
+ class ReaderConfigurationError(ValueError):
21
+ """The reader-tier configuration is unsafe to apply."""
22
+
23
+
24
+ def validate_reader_configuration(
25
+ *,
26
+ reader_scopes: Sequence[str],
27
+ admin_scopes: Sequence[str],
28
+ client_keys_raw: str,
29
+ ) -> None:
30
+ """Refuse an unsafe reader-tier configuration. A no-op when no reader scopes are set.
31
+
32
+ Raises:
33
+ ReaderConfigurationError: when reader scopes are set and the client-key
34
+ mapping fails the strict parser, is empty, or has a name containing
35
+ ``*``; a reader scope overlaps an administrator scope, starts with
36
+ ``access/`` or ``patient/``, is generic (``openid``, ``profile``,
37
+ ``email``, ``groups``) or ends in ``*.*``; or any administrator scope
38
+ starts with ``access/`` (a reader holding ``access/*.*`` would then be
39
+ an administrator).
40
+ """
41
+ if not reader_scopes:
42
+ return
43
+ try:
44
+ clients = parse_client_keys_strict(raw=client_keys_raw)
45
+ except ClientKeysFormatError as exc:
46
+ raise ReaderConfigurationError(f"the client-key mapping is invalid: {exc}") from exc
47
+ if not clients:
48
+ raise ReaderConfigurationError("the client-key mapping is empty")
49
+ if any(WILDCARD_SLUG in name for name in clients):
50
+ raise ReaderConfigurationError(
51
+ f"a client name contains '{WILDCARD_SLUG}', which collides with the wildcard slug"
52
+ )
53
+ admin_normalized = {scope.strip().casefold() for scope in admin_scopes}
54
+ for scope in reader_scopes:
55
+ normalized = scope.strip().casefold()
56
+ if normalized in admin_normalized:
57
+ raise ReaderConfigurationError("a reader scope overlaps an administrator scope")
58
+ if normalized.startswith(ACCESS_SCOPE_PREFIX) or normalized.startswith(PATIENT_SCOPE_PREFIX):
59
+ raise ReaderConfigurationError(
60
+ f"a reader scope starts with '{ACCESS_SCOPE_PREFIX}' or '{PATIENT_SCOPE_PREFIX}'"
61
+ )
62
+ if normalized in GENERIC_SCOPES:
63
+ raise ReaderConfigurationError("a reader scope is a generic scope every token carries")
64
+ if normalized.endswith("*.*"):
65
+ raise ReaderConfigurationError("a reader scope ends in '*.*'")
66
+ if any(scope.strip().casefold().startswith(ACCESS_SCOPE_PREFIX) for scope in admin_scopes):
67
+ raise ReaderConfigurationError(
68
+ f"an administrator scope starts with '{ACCESS_SCOPE_PREFIX}': "
69
+ "a reader holding the wildcard access scope would be an administrator"
70
+ )
@@ -0,0 +1,30 @@
1
+ """Scope predicates: the patient deny and the all-of match on required scopes."""
2
+
3
+ from collections.abc import Collection, Iterable
4
+
5
+ # A token carrying any patient-scoped grant is a patient or patient-app token and
6
+ # is never an administrator, even if it also holds an administrator scope. The
7
+ # check is a prefix match on the trimmed, casefolded scope, so ``Patient/*.read``
8
+ # matches but ``Patient.read`` (no slash) does not.
9
+ PATIENT_SCOPE_PREFIX = "patient/"
10
+
11
+
12
+ def has_patient_scope(*, scopes: Iterable[str]) -> bool:
13
+ """True when any scope starts with ``patient/`` (trimmed, case-insensitive)."""
14
+ return any(scope.strip().casefold().startswith(PATIENT_SCOPE_PREFIX) for scope in scopes)
15
+
16
+
17
+ def has_admin_scopes(*, scopes: Iterable[str], required_scopes: Collection[str]) -> bool:
18
+ """True when ``scopes`` holds every required scope exactly and no ``patient/`` scope.
19
+
20
+ An empty ``required_scopes`` is always False: ``set().issubset(anything)`` is
21
+ True, so an empty requirement (for example an unset setting) would otherwise
22
+ admit every verified token. This is the one check every administrator path
23
+ applies to the merged scope set.
24
+ """
25
+ if not required_scopes:
26
+ return False
27
+ held = set(scopes)
28
+ if has_patient_scope(scopes=held):
29
+ return False
30
+ return set(required_scopes).issubset(held)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: oidcauthlib
3
- Version: 3.0.30
3
+ Version: 3.1.0
4
4
  Summary: oidcauthlib
5
5
  Author-email: Imran Qureshi <imran.qureshi@bwell.com>
6
6
  License: Apache-2.0
@@ -69,3 +69,54 @@ scopes = await manager.get_scopes_from_user_info_async(access_token=token)
69
69
  malformed entry is logged and treated as a miss, and the refetched scopes overwrite the bad entry. A
70
70
  userinfo HTTP error, a missing provider or a mismatched subject is raised, so each service decides whether
71
71
  to fail closed or degrade.
72
+
73
+ ## Administrator and tenant-reader tiers (`oidcauthlib.authorization`)
74
+
75
+ Pure helpers that turn a caller's merged scopes (for example the result of `OidcUserInfoManager`) into a
76
+ tier: `admin` (unrestricted), `reader` (limited to the client keys its `access/<slug>.*` scopes select), or
77
+ denied. The subpackage reads no environment variable, does no I/O and imports nothing else from
78
+ `oidcauthlib`; the caller verifies the token, looks up the user and passes the configuration in.
79
+
80
+ ```python
81
+ from oidcauthlib.authorization import (
82
+ ClientSlugResolver,
83
+ parse_client_keys_lenient,
84
+ resolve_admin_access,
85
+ validate_reader_configuration,
86
+ )
87
+
88
+ RAW_CLIENTS = "One=key-1,Two=key-2" # the setting that holds the client-key mapping
89
+
90
+ # At startup: refuse an unsafe configuration (a no-op when no reader scopes are set).
91
+ validate_reader_configuration(
92
+ reader_scopes=["example/reader"],
93
+ admin_scopes=["example/admin"],
94
+ client_keys_raw=RAW_CLIENTS,
95
+ )
96
+
97
+ clients = ClientSlugResolver.from_client_keys(clients=parse_client_keys_lenient(raw=RAW_CLIENTS))
98
+ access = resolve_admin_access(
99
+ scopes=["example/reader", "access/one.*"],
100
+ admin_scopes=["example/admin"],
101
+ reader_scopes=["example/reader"],
102
+ clients=clients,
103
+ allow_all_tenants=False,
104
+ )
105
+ # access.tier is AdminTier.READER and access.allowed_client_keys == frozenset({"key-1"})
106
+ ```
107
+
108
+ - **Order:** any `patient/` scope (trimmed, case-insensitive) denies first; then holding every admin scope
109
+ gives `admin`; then every reader scope plus at least one `access/<slug>.*` that selects a client gives
110
+ `reader`; anything else is denied with a `DenialReason`. An empty admin or reader requirement admits nobody.
111
+ - **Slugs:** `access/<slug>.*` selects the client whose name, stripped and casefolded, equals the slug. Two
112
+ names that casefold alike make the slug ambiguous and it selects nothing. The suffix must be exactly `.*`.
113
+ `access/*.*` selects every client only when `allow_all_tenants=True`.
114
+ - **No default for "all tenants":** `allowed_client_keys` is `None` only for `admin`. A reader always has a
115
+ non-empty set and a denied caller always has `frozenset()`, so a denial can never be read as unrestricted.
116
+ `AdminAccess` enforces this when it is constructed.
117
+ - **Client-key mapping:** a `name -> key` map given as a JSON object or `One=key-1,Two=key-2`.
118
+ `parse_client_keys_lenient` keeps the permissive behavior (a malformed JSON object falls back to comma
119
+ parsing, an entry without `=` is dropped); `parse_client_keys_strict` refuses both, and refuses blank or
120
+ repeated names. Error messages name the rule, never a name or key.
121
+ - **Eligibility:** `from_client_keys(..., is_eligible=...)` takes a `(name, key) -> bool` strategy for
122
+ callers that exclude some clients; an excluded client is in no view and takes no part in ambiguity.
@@ -57,6 +57,12 @@ oidcauthlib/auth/well_known_configuration/auth_server_metadata_discovery.py
57
57
  oidcauthlib/auth/well_known_configuration/well_known_configuration_cache.py
58
58
  oidcauthlib/auth/well_known_configuration/well_known_configuration_cache_result.py
59
59
  oidcauthlib/auth/well_known_configuration/well_known_configuration_manager.py
60
+ oidcauthlib/authorization/__init__.py
61
+ oidcauthlib/authorization/admin_access.py
62
+ oidcauthlib/authorization/client_keys.py
63
+ oidcauthlib/authorization/client_slugs.py
64
+ oidcauthlib/authorization/reader_configuration.py
65
+ oidcauthlib/authorization/scopes.py
60
66
  oidcauthlib/cache_gate/__init__.py
61
67
  oidcauthlib/cache_gate/advisory_lock.py
62
68
  oidcauthlib/cache_gate/version_gate.py
@@ -1,43 +0,0 @@
1
- # oidcauthlib
2
-
3
- ## OIDC userinfo scopes (`OidcUserInfoManager`)
4
-
5
- Some providers (e.g. Okta employee access tokens) only carry `openid profile email groups` in the JWT;
6
- the scopes that authorize a caller appear only on the OIDC userinfo response.
7
- `oidcauthlib.auth.userinfo.oidc_userinfo_manager.OidcUserInfoManager` resolves a token's effective
8
- scopes from the token's own claims plus the userinfo endpoint, and caches the userinfo-derived scopes in
9
- a key-value store.
10
-
11
- ```python
12
- manager = OidcUserInfoManager(
13
- auth_config_reader=auth_config_reader,
14
- well_known_configuration_manager=well_known_configuration_manager,
15
- store=store, # py-key-value-aio store; yours, not shared with other services
16
- cache_collection="oidc-user-info-cache",
17
- cache_ttl_seconds=86400,
18
- fetch_timeout_seconds=30,
19
- scope_claims=["custom:scope"], # optional extra claims holding scopes
20
- group_claims=["groups"], # optional claims holding group names, used whole as scopes
21
- scope_remove_prefixes=["fhir/prod/"],
22
- )
23
- scopes = await manager.get_scopes_from_user_info_async(access_token=token)
24
- ```
25
-
26
- - **Scope derivation** follows fhir-server-ui's `jwtParser`: the `scope` claim (plus `scp`), then
27
- `scope_claims`, then `group_claims` (each value taken whole). Commas separate like spaces, results are
28
- de-duplicated, and `scope_remove_prefixes` are stripped (first match wins). Nothing beyond `scope`/`scp`
29
- is read unless configured.
30
- - **Provider** is matched to the token's `iss`: an exact `issuer`, else a `well_known_uri` on the same scheme,
31
- host and port whose path segments start with the issuer's. Only a token with no `iss` at all is matched by
32
- its client id. A token matching no provider raises `ValueError`; it is never sent to another provider.
33
- - **Subject check:** for a token that has a `sub`, the userinfo response must carry the same `sub`
34
- (OIDC Core 5.3.2); a missing or different one raises `ValueError` and nothing is cached.
35
- - **Cache** key is `oidc-userinfo-scopes:<issuer>:<client_id>:<sub>|v1` with each segment percent-encoded
36
- (so values containing `:` cannot collide, and two providers never share an entry); only the
37
- userinfo-derived scopes are stored, never the userinfo response. The token's own scopes are re-derived on every call. A token without
38
- `sub` or without an issuer, or an empty scope list, is not cached. Changes to a user's entitlements are visible after at most
39
- `cache_ttl_seconds`.
40
- - **Failures:** the cache never fails a lookup. A write failure is logged and swallowed; a read failure or a
41
- malformed entry is logged and treated as a miss, and the refetched scopes overwrite the bad entry. A
42
- userinfo HTTP error, a missing provider or a mismatched subject is raised, so each service decides whether
43
- to fail closed or degrade.
@@ -1 +0,0 @@
1
- 3.0.30
File without changes
File without changes
File without changes
File without changes