graphcore-kernel 0.1.0__py3-none-any.whl
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.
- graphcore/__init__.py +5 -0
- graphcore/agent_frontend/__init__.py +8 -0
- graphcore/agent_frontend/api.py +69 -0
- graphcore/agent_frontend/base/__init__.py +11 -0
- graphcore/agent_frontend/base/views.py +167 -0
- graphcore/agent_frontend/client.py +31 -0
- graphcore/agent_frontend/context.py +157 -0
- graphcore/agent_frontend/errors.py +12 -0
- graphcore/agent_frontend/loading.py +54 -0
- graphcore/agent_frontend/registry.py +42 -0
- graphcore/agent_frontend/render.py +207 -0
- graphcore/agent_frontend/server.py +103 -0
- graphcore/agent_frontend/signatures.py +35 -0
- graphcore/agent_frontend/testing.py +45 -0
- graphcore/agent_frontend/tests/__init__.py +0 -0
- graphcore/agent_frontend/tests/fakes.py +114 -0
- graphcore/agent_frontend/tests/test_frontend.py +447 -0
- graphcore/agent_frontend/tests/test_loading.py +83 -0
- graphcore/agent_frontend/tests/test_server.py +109 -0
- graphcore/agent_frontend/tools.py +137 -0
- graphcore/api/__init__.py +4 -0
- graphcore/api/graph_api.py +378 -0
- graphcore/api/predicate_codec.py +81 -0
- graphcore/api/tests/__init__.py +0 -0
- graphcore/api/tests/test_changed_entities.py +109 -0
- graphcore/api/tests/test_graph_api.py +290 -0
- graphcore/api/tests/test_graph_api_access.py +94 -0
- graphcore/api/tests/test_graph_api_grants.py +90 -0
- graphcore/api/tests/test_predicate_codec.py +83 -0
- graphcore/api/tests/test_subtree_query.py +79 -0
- graphcore/apps.py +71 -0
- graphcore/auth/__init__.py +1 -0
- graphcore/auth/authn/README.md +178 -0
- graphcore/auth/authn/__init__.py +3 -0
- graphcore/auth/authn/authenticator.py +120 -0
- graphcore/auth/authn/onboarding.py +105 -0
- graphcore/auth/authn/principals.py +20 -0
- graphcore/auth/authn/resource_metadata.py +43 -0
- graphcore/auth/authn/service_accounts.py +96 -0
- graphcore/auth/authn/testing.py +96 -0
- graphcore/auth/authn/tests/__init__.py +0 -0
- graphcore/auth/authn/tests/test_authenticator.py +145 -0
- graphcore/auth/authn/tests/test_onboarding.py +145 -0
- graphcore/auth/authn/tests/test_service_accounts.py +180 -0
- graphcore/auth/authn/users.py +59 -0
- graphcore/auth/authz/__init__.py +0 -0
- graphcore/auth/authz/access_port.py +120 -0
- graphcore/auth/authz/adapter/__init__.py +0 -0
- graphcore/auth/authz/adapter/default_access_adapter.py +556 -0
- graphcore/auth/authz/adapter/tests/__init__.py +0 -0
- graphcore/auth/authz/adapter/tests/test_default_adapter.py +543 -0
- graphcore/auth/authz/adapter/tests/test_entity_write_hooks.py +207 -0
- graphcore/auth/authz/adapter/tests/test_group_types.py +70 -0
- graphcore/auth/authz/adapter/tests/test_sync_support.py +209 -0
- graphcore/auth/authz/defaults.py +26 -0
- graphcore/auth/authz/kernel_policy.py +191 -0
- graphcore/auth/authz/kernel_writes.py +31 -0
- graphcore/auth/authz/lookups.py +25 -0
- graphcore/auth/authz/policy.py +403 -0
- graphcore/auth/authz/tests/__init__.py +0 -0
- graphcore/auth/authz/tests/test_can_contain.py +150 -0
- graphcore/auth/authz/tests/test_contained_by.py +167 -0
- graphcore/auth/authz/tests/test_creation.py +391 -0
- graphcore/auth/authz/tests/test_delete_permission.py +82 -0
- graphcore/auth/authz/tests/test_granted_to_me.py +160 -0
- graphcore/auth/authz/tests/test_integration.py +637 -0
- graphcore/auth/authz/tests/test_invites.py +184 -0
- graphcore/auth/authz/tests/test_kernel_policy.py +140 -0
- graphcore/auth/authz/tests/test_lockout.py +132 -0
- graphcore/auth/authz/tests/test_policy.py +329 -0
- graphcore/auth/authz/tests/test_primitives.py +73 -0
- graphcore/auth/authz/tests/test_principal_creation.py +62 -0
- graphcore/bootstrap/__init__.py +0 -0
- graphcore/bootstrap/deployment.py +67 -0
- graphcore/bootstrap/signals.py +16 -0
- graphcore/bootstrap/tests/__init__.py +0 -0
- graphcore/bootstrap/tests/test_deployment_seed.py +154 -0
- graphcore/broadcast/__init__.py +4 -0
- graphcore/broadcast/broadcaster.py +201 -0
- graphcore/broadcast/channels.py +56 -0
- graphcore/broadcast/tests/__init__.py +0 -0
- graphcore/broadcast/tests/test_broadcaster.py +444 -0
- graphcore/celery.py +14 -0
- graphcore/docs/AGENT_FRONTEND_TDD.md +389 -0
- graphcore/docs/ARCHITECTURE_PRINCIPLES.md +152 -0
- graphcore/docs/AUTHORIZATION_TECHNICAL_TDD.md +1379 -0
- graphcore/docs/ENTITY_REFERENCE_TDD.md +561 -0
- graphcore/docs/GRAPHAPI_FRONT_DOOR.md +173 -0
- graphcore/docs/RUNTIME.md +90 -0
- graphcore/docs/SCHEDULING_TDD.md +244 -0
- graphcore/docs/STRATEGY_EXECUTION_TDD.md +1043 -0
- graphcore/docs/VIEW_ENTITY_TDD.md +522 -0
- graphcore/docs/VIEW_SYSTEM_TDD.md +307 -0
- graphcore/docs/__init__.py +0 -0
- graphcore/docs/doc_topics.py +97 -0
- graphcore/docs/docs_discovery.py +64 -0
- graphcore/docs/public_api.py +56 -0
- graphcore/domain/__init__.py +0 -0
- graphcore/domain/entity/Entity.py +204 -0
- graphcore/domain/entity/__init__.py +0 -0
- graphcore/domain/entity/deployment/Deployment.py +25 -0
- graphcore/domain/entity/deployment/__init__.py +0 -0
- graphcore/domain/entity/grant/Grant.py +31 -0
- graphcore/domain/entity/grant/__init__.py +0 -0
- graphcore/domain/entity/group/Group.py +48 -0
- graphcore/domain/entity/group/README.md +88 -0
- graphcore/domain/entity/group/__init__.py +0 -0
- graphcore/domain/entity/invite/Invite.py +31 -0
- graphcore/domain/entity/invite/__init__.py +0 -0
- graphcore/domain/entity/request_template/RequestTemplate.py +48 -0
- graphcore/domain/entity/request_template/__init__.py +0 -0
- graphcore/domain/entity/request_template/tests/__init__.py +0 -0
- graphcore/domain/entity/request_template/tests/test_request_template.py +52 -0
- graphcore/domain/entity/service_account/ServiceAccount.py +41 -0
- graphcore/domain/entity/service_account/__init__.py +0 -0
- graphcore/domain/entity/strategy_request/StrategyRequest.py +61 -0
- graphcore/domain/entity/strategy_request/__init__.py +0 -0
- graphcore/domain/entity/strategy_request/tests/__init__.py +0 -0
- graphcore/domain/entity/strategy_request/tests/test_strategy_request_entity.py +35 -0
- graphcore/domain/entity/tests/__init__.py +0 -0
- graphcore/domain/entity/tests/test_entity.py +227 -0
- graphcore/domain/entity/tests/test_grant_group_entities.py +36 -0
- graphcore/domain/entity/tests/test_write_once_fields.py +98 -0
- graphcore/domain/entity/user/User.py +39 -0
- graphcore/domain/entity/user/__init__.py +0 -0
- graphcore/domain/entity/user/tests/__init__.py +0 -0
- graphcore/domain/entity/user/tests/test_user_entity.py +33 -0
- graphcore/domain/entity/view/View.py +37 -0
- graphcore/domain/entity/view/__init__.py +0 -0
- graphcore/domain/entity/view/position.py +78 -0
- graphcore/domain/entity/view/tests/__init__.py +0 -0
- graphcore/domain/entity/view/tests/test_position.py +71 -0
- graphcore/domain/entity/view/tests/test_view_entity.py +134 -0
- graphcore/domain/strategy/BaseStrategy.py +759 -0
- graphcore/domain/strategy/DeploymentStrategies.py +55 -0
- graphcore/domain/strategy/GrantStrategies.py +189 -0
- graphcore/domain/strategy/GroupStrategies.py +193 -0
- graphcore/domain/strategy/InviteStrategies.py +84 -0
- graphcore/domain/strategy/RequestTemplateStrategies.py +126 -0
- graphcore/domain/strategy/ViewStrategies.py +219 -0
- graphcore/domain/strategy/__init__.py +0 -0
- graphcore/domain/strategy/runner.py +84 -0
- graphcore/domain/strategy/session.py +56 -0
- graphcore/domain/strategy/tests/BaseStrategyTest.py +167 -0
- graphcore/domain/strategy/tests/__init__.py +0 -0
- graphcore/domain/strategy/tests/test_BaseStrategies.py +870 -0
- graphcore/domain/strategy/tests/test_grant_strategies.py +245 -0
- graphcore/domain/strategy/tests/test_group_strategies.py +99 -0
- graphcore/domain/strategy/tests/test_runner.py +220 -0
- graphcore/domain/strategy/tests/test_strategy_locks.py +446 -0
- graphcore/domain/strategy/tests/test_utils.py +95 -0
- graphcore/domain/strategy/tests/test_view_strategies.py +436 -0
- graphcore/errors.py +145 -0
- graphcore/execution/README.md +97 -0
- graphcore/execution/StrategyExecutorService.py +333 -0
- graphcore/execution/__init__.py +0 -0
- graphcore/execution/dispatcher.py +19 -0
- graphcore/execution/environments/__init__.py +0 -0
- graphcore/execution/environments/celery.py +59 -0
- graphcore/execution/environments/in_process.py +55 -0
- graphcore/execution/local_session.py +117 -0
- graphcore/execution/redis_run_events.py +74 -0
- graphcore/execution/requests.py +22 -0
- graphcore/execution/run_events.py +85 -0
- graphcore/execution/strategy_context.py +54 -0
- graphcore/execution/tasks.py +34 -0
- graphcore/execution/tests/__init__.py +5 -0
- graphcore/execution/tests/contract.py +171 -0
- graphcore/execution/tests/support.py +310 -0
- graphcore/execution/tests/test_dispatchers.py +76 -0
- graphcore/execution/tests/test_executor.py +368 -0
- graphcore/execution/tests/test_local_session.py +95 -0
- graphcore/execution/tests/test_reconcile_runs.py +134 -0
- graphcore/execution/tests/test_run_events.py +106 -0
- graphcore/execution/tests/test_strategy_context.py +62 -0
- graphcore/gateway/__init__.py +1 -0
- graphcore/gateway/remote.py +35 -0
- graphcore/gateway/tests/__init__.py +0 -0
- graphcore/gateway/tests/test_remote.py +30 -0
- graphcore/graph/EntityService.py +710 -0
- graphcore/graph/__init__.py +0 -0
- graphcore/graph/entity_cache.py +152 -0
- graphcore/graph/tests/__init__.py +4 -0
- graphcore/graph/tests/test_EntityService.py +908 -0
- graphcore/graph/tests/test_EntityService_list.py +170 -0
- graphcore/graph/tests/test_EntityService_model_resolution.py +339 -0
- graphcore/graph/tests/test_EntityService_referrers.py +236 -0
- graphcore/graph/tests/test_EntityService_routing.py +119 -0
- graphcore/graph/tests/test_dependent_on.py +141 -0
- graphcore/graph/tests/test_engine_is_type_agnostic.py +25 -0
- graphcore/graph/tests/test_engine_resolves_read_permission.py +93 -0
- graphcore/graph/tests/test_entity_cache.py +159 -0
- graphcore/graph/tests/test_null_entity_cache.py +12 -0
- graphcore/management/__init__.py +0 -0
- graphcore/management/commands/__init__.py +0 -0
- graphcore/management/commands/dev_reset.py +18 -0
- graphcore/management/commands/graphcore_createadmin.py +65 -0
- graphcore/management/commands/graphcore_policy.py +59 -0
- graphcore/management/commands/graphcore_status.py +98 -0
- graphcore/management/tests/__init__.py +0 -0
- graphcore/management/tests/test_createadmin.py +78 -0
- graphcore/management/tests/test_policy_command.py +46 -0
- graphcore/management/tests/test_status_command.py +85 -0
- graphcore/migrations/0001_initial.py +186 -0
- graphcore/migrations/0002_invite.py +26 -0
- graphcore/migrations/__init__.py +0 -0
- graphcore/models.py +11 -0
- graphcore/persistence/ENTITY_REPOSITORY_TECHNICAL_TDD.md +396 -0
- graphcore/persistence/__init__.py +6 -0
- graphcore/persistence/django/__init__.py +0 -0
- graphcore/persistence/django/backends.py +43 -0
- graphcore/persistence/django/bindings.py +28 -0
- graphcore/persistence/django/cache.py +38 -0
- graphcore/persistence/django/compiler.py +214 -0
- graphcore/persistence/django/identity.py +18 -0
- graphcore/persistence/django/models.py +252 -0
- graphcore/persistence/django/repository.py +525 -0
- graphcore/persistence/django/tests/__init__.py +0 -0
- graphcore/persistence/django/tests/test_backends.py +68 -0
- graphcore/persistence/django/tests/test_compiler.py +269 -0
- graphcore/persistence/django/tests/test_repository.py +472 -0
- graphcore/persistence/django/tests/test_shared_column.py +120 -0
- graphcore/persistence/django/tests/test_threads.py +50 -0
- graphcore/persistence/django/tests/test_update_shape.py +175 -0
- graphcore/persistence/django/threads.py +38 -0
- graphcore/persistence/repository.py +172 -0
- graphcore/persistence/tests/__init__.py +0 -0
- graphcore/persistence/tests/contract.py +688 -0
- graphcore/persistence/tests/evaluate.py +51 -0
- graphcore/persistence/tests/fixtures.py +32 -0
- graphcore/persistence/tests/memory.py +263 -0
- graphcore/persistence/tests/test_memory_repository.py +10 -0
- graphcore/persistence/tests/test_query_types.py +127 -0
- graphcore/public/__init__.py +9 -0
- graphcore/public/api.py +9 -0
- graphcore/public/apps.py +10 -0
- graphcore/public/auth/__init__.py +1 -0
- graphcore/public/auth/grants.py +7 -0
- graphcore/public/auth/onboarding.py +8 -0
- graphcore/public/auth/perms.py +7 -0
- graphcore/public/auth/policy.py +10 -0
- graphcore/public/auth/roles.py +8 -0
- graphcore/public/auth/subjects.py +7 -0
- graphcore/public/entities/__init__.py +32 -0
- graphcore/public/errors.py +19 -0
- graphcore/public/persistence/__init__.py +44 -0
- graphcore/public/persistence/django.py +24 -0
- graphcore/public/scheduling.py +23 -0
- graphcore/public/strategies/__init__.py +85 -0
- graphcore/public/test_settings.py +16 -0
- graphcore/public/testing.py +47 -0
- graphcore/registry/EntityDirectory.py +246 -0
- graphcore/registry/README.md +147 -0
- graphcore/registry/StrategyDirectory.py +308 -0
- graphcore/registry/TYPE_METADATA_PLACEMENT.md +66 -0
- graphcore/registry/__init__.py +0 -0
- graphcore/registry/app_discovery.py +108 -0
- graphcore/registry/decorators.py +77 -0
- graphcore/registry/discovery.py +111 -0
- graphcore/registry/registry.py +79 -0
- graphcore/registry/tests/__init__.py +0 -0
- graphcore/registry/tests/test_agent_frontend_discovery.py +56 -0
- graphcore/registry/tests/test_app_config.py +36 -0
- graphcore/registry/tests/test_discovery.py +147 -0
- graphcore/registry/tests/test_entity_directory_storage.py +73 -0
- graphcore/registry/tests/test_import_package.py +87 -0
- graphcore/registry/tests/test_principal_flag.py +67 -0
- graphcore/registry/tests/test_strategy_directory.py +29 -0
- graphcore/routes/__init__.py +116 -0
- graphcore/routes/tests/__init__.py +0 -0
- graphcore/routes/tests/test_routes.py +90 -0
- graphcore/runtime.py +243 -0
- graphcore/scheduling/__init__.py +0 -0
- graphcore/scheduling/beat_scheduler.py +164 -0
- graphcore/scheduling/beat_tasks.py +63 -0
- graphcore/scheduling/scheduler.py +37 -0
- graphcore/scheduling/tests/__init__.py +0 -0
- graphcore/scheduling/tests/contract.py +136 -0
- graphcore/scheduling/tests/memory.py +42 -0
- graphcore/scheduling/tests/test_beat_scheduler.py +87 -0
- graphcore/scheduling/tests/test_memory_scheduler.py +15 -0
- graphcore/scheduling/tests/test_ticks.py +143 -0
- graphcore/tasks.py +9 -0
- graphcore/test_settings.py +78 -0
- graphcore/testing/__init__.py +0 -0
- graphcore/testing/case.py +112 -0
- graphcore/testing/runner.py +32 -0
- graphcore/testing/settings.py +26 -0
- graphcore/testing/tests/__init__.py +0 -0
- graphcore/testing/tests/agent_view_fixture.py +19 -0
- graphcore/testing/tests/test_case_and_runner.py +219 -0
- graphcore/testing/tests/test_settings_for_apps.py +50 -0
- graphcore/tests/__init__.py +0 -0
- graphcore/tests/ids.py +14 -0
- graphcore/tests/public_api_manifest.py +102 -0
- graphcore/tests/runs.py +7 -0
- graphcore/tests/test_app_discovery.py +90 -0
- graphcore/tests/test_composition_boundaries.py +231 -0
- graphcore/tests/test_docs_discovery.py +108 -0
- graphcore/tests/test_no_print.py +70 -0
- graphcore/tests/test_packaging.py +64 -0
- graphcore/tests/test_public_api_boundaries.py +229 -0
- graphcore/tests/test_public_api_contract.py +62 -0
- graphcore/tests/test_public_api_docs.py +28 -0
- graphcore/tests/test_runtime.py +42 -0
- graphcore/tests/test_shared_type_boundaries.py +128 -0
- graphcore/tests/test_shared_types.py +144 -0
- graphcore/tests/test_test_settings.py +45 -0
- graphcore/transport/__init__.py +0 -0
- graphcore/transport/agent_asgi.py +68 -0
- graphcore/transport/agent_client.py +85 -0
- graphcore/transport/channel_layer.py +68 -0
- graphcore/transport/consumers.py +507 -0
- graphcore/transport/routing.py +6 -0
- graphcore/transport/tests/__init__.py +0 -0
- graphcore/transport/tests/test_agent_client.py +31 -0
- graphcore/transport/tests/test_api_views.py +733 -0
- graphcore/transport/tests/test_channel_layer.py +96 -0
- graphcore/transport/tests/test_consumers.py +963 -0
- graphcore/transport/tests/test_resource_metadata.py +67 -0
- graphcore/transport/urls.py +29 -0
- graphcore/transport/views.py +358 -0
- graphcore/types/__init__.py +4 -0
- graphcore/types/access.py +114 -0
- graphcore/types/api.py +76 -0
- graphcore/types/entities.py +100 -0
- graphcore/types/entity_id.py +85 -0
- graphcore/types/execution.py +41 -0
- graphcore/types/identity.py +20 -0
- graphcore/types/onboarding.py +20 -0
- graphcore/types/query.py +116 -0
- graphcore/types/schedules.py +91 -0
- graphcore/types/strategy.py +73 -0
- graphcore/types/tests/__init__.py +0 -0
- graphcore/types/tests/test_entity_id.py +50 -0
- graphcore/urls.py +5 -0
- graphcore_kernel-0.1.0.dist-info/METADATA +94 -0
- graphcore_kernel-0.1.0.dist-info/RECORD +343 -0
- graphcore_kernel-0.1.0.dist-info/WHEEL +5 -0
- graphcore_kernel-0.1.0.dist-info/entry_points.txt +2 -0
- graphcore_kernel-0.1.0.dist-info/licenses/LICENSE +202 -0
- graphcore_kernel-0.1.0.dist-info/licenses/NOTICE +2 -0
- graphcore_kernel-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Type policy for the kernel's own authorization-machinery entity types.
|
|
2
|
+
|
|
3
|
+
Configured once during discovery, before the policy is frozen - see
|
|
4
|
+
docs/AUTHORIZATION_TECHNICAL_TDD.md (Grant storage, Groups, Type policy).
|
|
5
|
+
"""
|
|
6
|
+
from django.conf import settings
|
|
7
|
+
|
|
8
|
+
from graphcore.auth.authz.policy import AccessPolicy
|
|
9
|
+
from graphcore.types.access import Create, Delete, ManageAccess, Read, Write
|
|
10
|
+
from graphcore.auth.authz.defaults import ADMIN, MEMBER
|
|
11
|
+
from graphcore.domain.entity.Entity import Entity
|
|
12
|
+
from graphcore.domain.entity.deployment.Deployment import Deployment
|
|
13
|
+
from graphcore.domain.entity.grant.Grant import Grant
|
|
14
|
+
from graphcore.domain.entity.group.Group import Group
|
|
15
|
+
from graphcore.domain.entity.invite.Invite import Invite
|
|
16
|
+
from graphcore.domain.entity.request_template.RequestTemplate import RequestTemplate
|
|
17
|
+
from graphcore.domain.entity.service_account.ServiceAccount import ServiceAccount
|
|
18
|
+
from graphcore.domain.entity.strategy_request.StrategyRequest import StrategyRequest
|
|
19
|
+
from graphcore.domain.entity.user.User import User
|
|
20
|
+
from graphcore.domain.entity.view.View import View
|
|
21
|
+
from graphcore.domain.strategy.BaseStrategy import (
|
|
22
|
+
CreateEntity, DeleteEntity, SetAttributes,
|
|
23
|
+
)
|
|
24
|
+
from graphcore.domain.strategy.DeploymentStrategies import SetNewUserDefaults
|
|
25
|
+
from graphcore.domain.strategy.GrantStrategies import (
|
|
26
|
+
ChangeGrantRole,
|
|
27
|
+
CreateGrant,
|
|
28
|
+
RevokeGrant,
|
|
29
|
+
)
|
|
30
|
+
from graphcore.domain.strategy.InviteStrategies import CreateInvite
|
|
31
|
+
from graphcore.domain.strategy.GroupStrategies import (
|
|
32
|
+
AddMember,
|
|
33
|
+
CreateGroup,
|
|
34
|
+
RemoveMember,
|
|
35
|
+
ModifyGroup,
|
|
36
|
+
)
|
|
37
|
+
from graphcore.domain.strategy.RequestTemplateStrategies import (
|
|
38
|
+
CreateRequestTemplate,
|
|
39
|
+
ManageRequestTemplate,
|
|
40
|
+
)
|
|
41
|
+
from graphcore.domain.strategy.ViewStrategies import CreateView, SetViewState
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def configure(policy: AccessPolicy) -> None:
|
|
45
|
+
# CreateGrant targets the resource being shared, which can be any
|
|
46
|
+
# type, so its permission has to reach every type via the base class.
|
|
47
|
+
# ChangeGrantRole/RevokeGrant target Grant
|
|
48
|
+
# exclusively and AddMember/RemoveMember/ModifyGroup target Group
|
|
49
|
+
# exclusively, so those are declared on their own type instead; a
|
|
50
|
+
# Group subclass inherits them.
|
|
51
|
+
policy.define(
|
|
52
|
+
Entity,
|
|
53
|
+
strategies={
|
|
54
|
+
CreateGrant: ManageAccess(),
|
|
55
|
+
CreateInvite: ManageAccess(),
|
|
56
|
+
CreateEntity: Create(),
|
|
57
|
+
CreateGroup: Create(),
|
|
58
|
+
CreateView: Create(),
|
|
59
|
+
},
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# Whether profiles are visible varies per deployment, so it is a setting.
|
|
63
|
+
# A principal contains nothing; what a user creates is top-level.
|
|
64
|
+
policy.define(
|
|
65
|
+
User,
|
|
66
|
+
public=[Read()] if getattr(settings, 'GRAPHCORE_PUBLIC_USER_READ', True) else [],
|
|
67
|
+
can_contain=[],
|
|
68
|
+
)
|
|
69
|
+
# Readable on the same terms as users, so apps and people can find one to
|
|
70
|
+
# grant it access; only the kernel writes them.
|
|
71
|
+
policy.define(
|
|
72
|
+
ServiceAccount,
|
|
73
|
+
public=[Read()] if getattr(settings, 'GRAPHCORE_PUBLIC_USER_READ', True) else [],
|
|
74
|
+
strategies={},
|
|
75
|
+
other_strategies=False,
|
|
76
|
+
can_contain=[],
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# Holds the grants that decide who may create at the top level. It
|
|
80
|
+
# contains only grants, so its grants reach nothing else.
|
|
81
|
+
policy.define(
|
|
82
|
+
Deployment,
|
|
83
|
+
shareable=True,
|
|
84
|
+
can_contain=[Grant],
|
|
85
|
+
creatable=False,
|
|
86
|
+
roles=[MEMBER, ADMIN],
|
|
87
|
+
strategies={
|
|
88
|
+
CreateEntity: Create(),
|
|
89
|
+
CreateGroup: Create(),
|
|
90
|
+
SetViewState: Create(),
|
|
91
|
+
CreateView: Create(),
|
|
92
|
+
SetNewUserDefaults: ManageAccess(),
|
|
93
|
+
CreateGrant: ManageAccess(),
|
|
94
|
+
CreateRequestTemplate: Create(),
|
|
95
|
+
},
|
|
96
|
+
other_strategies=False,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
# A grant is mutated only through the grant strategies - "grants on
|
|
100
|
+
# nothing govern nothing" needs generic create and delete absent here.
|
|
101
|
+
# Only those who can manage access to a resource see who has it.
|
|
102
|
+
policy.define(
|
|
103
|
+
Grant,
|
|
104
|
+
create=ManageAccess(),
|
|
105
|
+
read=ManageAccess(),
|
|
106
|
+
delete=ManageAccess(),
|
|
107
|
+
can_contain=[],
|
|
108
|
+
strategies={
|
|
109
|
+
CreateGrant: ManageAccess(),
|
|
110
|
+
ChangeGrantRole: ManageAccess(),
|
|
111
|
+
RevokeGrant: ManageAccess(),
|
|
112
|
+
},
|
|
113
|
+
other_strategies=False,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
# Like a grant, an invite is seen and revoked only by those who can
|
|
117
|
+
# manage access to its resource.
|
|
118
|
+
policy.define(
|
|
119
|
+
Invite,
|
|
120
|
+
create=ManageAccess(),
|
|
121
|
+
read=ManageAccess(),
|
|
122
|
+
delete=ManageAccess(),
|
|
123
|
+
can_contain=[],
|
|
124
|
+
strategies={
|
|
125
|
+
CreateInvite: ManageAccess(),
|
|
126
|
+
DeleteEntity: ManageAccess(),
|
|
127
|
+
},
|
|
128
|
+
other_strategies=False,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
# Groups are made only by CreateGroup, so the generic create is
|
|
132
|
+
# absent; listing it here admits the new group, and a group holds only
|
|
133
|
+
# its own grants. A key names a group in deployment policy, so only a
|
|
134
|
+
# deployment administrator gives one.
|
|
135
|
+
policy.define(
|
|
136
|
+
Group,
|
|
137
|
+
shareable=True,
|
|
138
|
+
can_contain=[Grant],
|
|
139
|
+
deployment_fields={'key': ManageAccess()},
|
|
140
|
+
strategies={
|
|
141
|
+
CreateGrant: ManageAccess(),
|
|
142
|
+
ChangeGrantRole: Write(),
|
|
143
|
+
RevokeGrant: Write(),
|
|
144
|
+
AddMember: ManageAccess(),
|
|
145
|
+
RemoveMember: ManageAccess(),
|
|
146
|
+
ModifyGroup: Write(),
|
|
147
|
+
CreateGroup: Create(),
|
|
148
|
+
SetAttributes: Write(),
|
|
149
|
+
DeleteEntity: Write(),
|
|
150
|
+
},
|
|
151
|
+
other_strategies=False,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
# Views hold only views and their own grants; data is shown by
|
|
155
|
+
# reference. Granting on a view shares every view inside it.
|
|
156
|
+
policy.define(
|
|
157
|
+
View,
|
|
158
|
+
shareable=True,
|
|
159
|
+
can_contain=[View, Grant, Invite],
|
|
160
|
+
strategies={
|
|
161
|
+
SetViewState: Write(),
|
|
162
|
+
CreateView: Create(),
|
|
163
|
+
DeleteEntity: Delete(),
|
|
164
|
+
CreateGrant: ManageAccess(),
|
|
165
|
+
CreateInvite: ManageAccess(),
|
|
166
|
+
},
|
|
167
|
+
other_strategies=False,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
# A request is written only by the executor, in kernel-internal context,
|
|
171
|
+
# and is read by the principal it runs as.
|
|
172
|
+
policy.define(
|
|
173
|
+
StrategyRequest,
|
|
174
|
+
creatable=False,
|
|
175
|
+
can_contain=[],
|
|
176
|
+
strategies={},
|
|
177
|
+
other_strategies=False,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
# Only the template strategies write a template, so a schedule is always
|
|
181
|
+
# validated before it is saved.
|
|
182
|
+
policy.define(
|
|
183
|
+
RequestTemplate,
|
|
184
|
+
can_contain=[],
|
|
185
|
+
strategies={
|
|
186
|
+
CreateRequestTemplate: Create(),
|
|
187
|
+
ManageRequestTemplate: Write(),
|
|
188
|
+
DeleteEntity: Delete(),
|
|
189
|
+
},
|
|
190
|
+
other_strategies=False,
|
|
191
|
+
)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""The fixed grant and membership writes the kernel makes on its own
|
|
2
|
+
authority: deployment seeding and applying onboarding. Callers open
|
|
3
|
+
`kernel_internal_context()`; application code never runs inside it (see
|
|
4
|
+
docs/AUTHORIZATION_TECHNICAL_TDD.md, Kernel-internal writes)."""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from graphcore.auth.authz.lookups import find_grant
|
|
8
|
+
from graphcore.domain.entity.grant.Grant import Grant
|
|
9
|
+
from graphcore.domain.entity.group.Group import Group
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
async def grant(entity_service, resource_id: str, subject_id: str, role_name: str, principal) -> Grant:
|
|
13
|
+
"""Create the grant, or re-role the existing one for the pair."""
|
|
14
|
+
existing = await find_grant(entity_service, resource_id, subject_id)
|
|
15
|
+
if existing is not None:
|
|
16
|
+
if existing.role_name == role_name:
|
|
17
|
+
return existing
|
|
18
|
+
existing.role_name = role_name
|
|
19
|
+
return await entity_service.save_entity(existing, principal)
|
|
20
|
+
new_grant = entity_service.create(Grant)
|
|
21
|
+
new_grant.subject_id = subject_id
|
|
22
|
+
new_grant.role_name = role_name
|
|
23
|
+
new_grant.set_parent(resource_id)
|
|
24
|
+
return await entity_service.save_entity(new_grant, principal)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
async def add_member(entity_service, group: Group, principal_entity_id: str, principal) -> Group:
|
|
28
|
+
if principal_entity_id in group.member_ids:
|
|
29
|
+
return group
|
|
30
|
+
group.add_member(principal_entity_id)
|
|
31
|
+
return await entity_service.save_entity(group, principal)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Queries for grants and groups by their identifying fields."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
from graphcore.domain.entity.grant.Grant import Grant
|
|
7
|
+
from graphcore.domain.entity.group.Group import Group
|
|
8
|
+
from graphcore.types.query import AllOf, Equal
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
async def find_grant(entity_service, resource_id: str, subject_id: str) -> Optional[Grant]:
|
|
12
|
+
grants = await entity_service.find_entities(AllOf((
|
|
13
|
+
Equal('entity_type_id', Grant.get_entity_type_id()),
|
|
14
|
+
Equal('parent_id', resource_id),
|
|
15
|
+
Equal('subject_id', subject_id),
|
|
16
|
+
)))
|
|
17
|
+
return next(iter(grants.values()), None)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def find_group_by_key(entity_service, key: str) -> Optional[Group]:
|
|
21
|
+
groups = await entity_service.find_entities(AllOf((
|
|
22
|
+
Equal('entity_type_id', Group.get_entity_type_id()),
|
|
23
|
+
Equal('key', key),
|
|
24
|
+
)))
|
|
25
|
+
return next(iter(groups.values()), None)
|
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""Access policy: one authorization declaration per entity type.
|
|
2
|
+
|
|
3
|
+
An application's configurator calls ``policy.define(EntityType, ...)`` once
|
|
4
|
+
for each type it registered, ``policy.extend(OtherAppsType, roles=[...], strategies={...})`` to
|
|
5
|
+
add roles and the app's own strategies to a type another app owns, and ``policy.declare_group(...)`` for
|
|
6
|
+
groups every deployment should have. ``policy.describe(EntityType)`` returns
|
|
7
|
+
a type's complete effective policy.
|
|
8
|
+
|
|
9
|
+
Declarations are keyed by the entity class itself so every caller that has
|
|
10
|
+
``type(entity)`` in hand - the executor, the persistence chokepoint - looks
|
|
11
|
+
policy up with no registry round trip. Policy closes once application loading
|
|
12
|
+
finishes, so code generated after load cannot widen its own authorization.
|
|
13
|
+
See ``docs/AUTHORIZATION_TECHNICAL_TDD.md`` (Type policy).
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from contextlib import contextmanager
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from types import MappingProxyType
|
|
20
|
+
from typing import Mapping, Optional, Sequence, Type
|
|
21
|
+
|
|
22
|
+
from graphcore.types.access import Create, Delete, Perm, Read, Role, Write
|
|
23
|
+
from graphcore.auth.authz.defaults import DEFAULT_ROLES
|
|
24
|
+
from graphcore.errors import Forbidden, KernelError
|
|
25
|
+
from graphcore.registry.StrategyDirectory import StrategyDirectory
|
|
26
|
+
|
|
27
|
+
KERNEL_APP_ID = 'graphcore'
|
|
28
|
+
|
|
29
|
+
_UNSET = object()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class PolicyClosedError(KernelError):
|
|
33
|
+
"""Raised when a declaration is attempted after policy closure."""
|
|
34
|
+
|
|
35
|
+
code = 'policy_closed'
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class EffectivePolicy:
|
|
40
|
+
"""A type's complete effective policy, as `AccessPolicy.describe` resolves it."""
|
|
41
|
+
|
|
42
|
+
shareable: bool
|
|
43
|
+
roles: tuple[Role, ...]
|
|
44
|
+
strategies: Mapping[type, Perm]
|
|
45
|
+
"""Declared permission per strategy, merged with base classes. Strategies
|
|
46
|
+
not listed need the type's read permission if read-only, otherwise Write."""
|
|
47
|
+
allowed_strategies: Optional[frozenset[type]]
|
|
48
|
+
"""The only strategies allowed on the type, or None when any may run."""
|
|
49
|
+
create: Perm
|
|
50
|
+
creatable: bool
|
|
51
|
+
public: frozenset[Perm]
|
|
52
|
+
read: Perm
|
|
53
|
+
"""The permission that reading an entity of this type requires."""
|
|
54
|
+
delete: Perm
|
|
55
|
+
"""The permission that deleting an entity of this type requires."""
|
|
56
|
+
can_contain: Optional[tuple[type, ...]]
|
|
57
|
+
"""The types an entity of this type may directly contain (subclasses
|
|
58
|
+
included), or None when it may contain any type."""
|
|
59
|
+
contained_by: Optional[tuple[type, ...]]
|
|
60
|
+
"""The types an entity of this type may be placed directly inside
|
|
61
|
+
(subclasses included), or None when it may have any parent or none."""
|
|
62
|
+
deployment_fields: Mapping[str, Perm]
|
|
63
|
+
"""Fields only a principal holding the given permission on the
|
|
64
|
+
deployment may set to a value."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class AccessPolicy:
|
|
68
|
+
"""Instance-owned type authorization declarations."""
|
|
69
|
+
|
|
70
|
+
def __init__(self, strategy_directory=StrategyDirectory):
|
|
71
|
+
self.strategy_directory = strategy_directory
|
|
72
|
+
# Set by `Registry`; used for the principal-type default of `creatable`
|
|
73
|
+
# and to resolve parent types for `can_contain` and `contained_by`.
|
|
74
|
+
self.entity_directory = None
|
|
75
|
+
self._defined: dict[type, dict] = {}
|
|
76
|
+
self._extended: dict[type, list[tuple[Role, Optional[str]]]] = {}
|
|
77
|
+
self._extended_strategies: dict[type, dict[type, Perm]] = {}
|
|
78
|
+
self._declared_groups: dict[str, str] = {}
|
|
79
|
+
self._declaring_app_id: Optional[str] = None
|
|
80
|
+
self._described: dict[type, EffectivePolicy] = {}
|
|
81
|
+
self._closed = False
|
|
82
|
+
|
|
83
|
+
def _check_open(self) -> None:
|
|
84
|
+
if self._closed:
|
|
85
|
+
raise PolicyClosedError(
|
|
86
|
+
"Type policy is closed - declarations are only valid during application load."
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
@contextmanager
|
|
90
|
+
def declaring_app(self, app_id: str):
|
|
91
|
+
"""Discovery runs each app's configurator inside this, so a
|
|
92
|
+
declaration can be checked against the app making it."""
|
|
93
|
+
previous, self._declaring_app_id = self._declaring_app_id, app_id
|
|
94
|
+
try:
|
|
95
|
+
yield
|
|
96
|
+
finally:
|
|
97
|
+
self._declaring_app_id = previous
|
|
98
|
+
|
|
99
|
+
# --- declarations -----------------------------------------------------
|
|
100
|
+
|
|
101
|
+
def define(
|
|
102
|
+
self,
|
|
103
|
+
entity_type: Type,
|
|
104
|
+
*,
|
|
105
|
+
shareable: bool = _UNSET,
|
|
106
|
+
roles: list[Role] = _UNSET,
|
|
107
|
+
strategies: dict[type, Perm] = _UNSET,
|
|
108
|
+
other_strategies: bool = _UNSET,
|
|
109
|
+
create: Perm = _UNSET,
|
|
110
|
+
creatable: bool = _UNSET,
|
|
111
|
+
public: list[Perm] = _UNSET,
|
|
112
|
+
read: Perm = _UNSET,
|
|
113
|
+
delete: Perm = _UNSET,
|
|
114
|
+
can_contain: Optional[Sequence[type]] = _UNSET,
|
|
115
|
+
contained_by: Optional[Sequence[type]] = _UNSET,
|
|
116
|
+
deployment_fields: dict[str, Perm] = _UNSET,
|
|
117
|
+
) -> None:
|
|
118
|
+
"""Declare `entity_type`'s authorization, once, from the app that
|
|
119
|
+
registered it. Every argument is optional; an argument not passed is
|
|
120
|
+
taken from the nearest base class that passed it, else its default.
|
|
121
|
+
|
|
122
|
+
- shareable (False): the type can hold grants.
|
|
123
|
+
- roles (viewer, editor, admin): the complete list of roles that can
|
|
124
|
+
be granted on it. Other apps add roles with `extend`.
|
|
125
|
+
- strategies ({}): the permission each listed strategy requires on
|
|
126
|
+
this type. Merged with base classes' entries. Unlisted strategies
|
|
127
|
+
need the type's read permission if read-only, otherwise Write.
|
|
128
|
+
- other_strategies (True): False makes the keys of `strategies` an
|
|
129
|
+
allowlist - only the strategies listed in this call may target or
|
|
130
|
+
write the type.
|
|
131
|
+
- create (Create()): permission needed on the parent to create one;
|
|
132
|
+
on the deployment when it has no parent. Use a `CreatePermission`
|
|
133
|
+
subclass for a permission owners should not hold implicitly.
|
|
134
|
+
- creatable (True, False for principal types): False means only
|
|
135
|
+
kernel code creates it.
|
|
136
|
+
- public (()): permissions every signed-in principal holds on every
|
|
137
|
+
entity of this type.
|
|
138
|
+
- read (Read()): the permission needed to read an entity of this type.
|
|
139
|
+
- delete (Delete()): the permission needed on an entity of this type
|
|
140
|
+
to delete it and everything it contains.
|
|
141
|
+
- can_contain (None): the types that may be placed directly inside an
|
|
142
|
+
entity of this type, subclasses included; None allows any type and
|
|
143
|
+
[] allows none. Checked on every write, kernel writes included.
|
|
144
|
+
- contained_by (None): the types an entity of this type may be placed
|
|
145
|
+
directly inside, subclasses included; None allows any parent or
|
|
146
|
+
none. When set, the entity is never top-level. Checked on every
|
|
147
|
+
create and move, kernel writes included.
|
|
148
|
+
- deployment_fields ({}): fields only a principal holding the given
|
|
149
|
+
permission on the deployment may set to a value, on create or
|
|
150
|
+
change. Merged with base classes' entries.
|
|
151
|
+
"""
|
|
152
|
+
self._check_open()
|
|
153
|
+
if entity_type in self._defined:
|
|
154
|
+
raise ValueError(f"Policy for {entity_type.__name__} is already defined")
|
|
155
|
+
self._check_owner(entity_type)
|
|
156
|
+
|
|
157
|
+
fields = {
|
|
158
|
+
name: value for name, value in (
|
|
159
|
+
('shareable', shareable), ('roles', roles),
|
|
160
|
+
('strategies', strategies), ('other_strategies', other_strategies),
|
|
161
|
+
('create', create), ('creatable', creatable), ('public', public),
|
|
162
|
+
('read', read), ('delete', delete), ('can_contain', can_contain),
|
|
163
|
+
('contained_by', contained_by), ('deployment_fields', deployment_fields),
|
|
164
|
+
) if value is not _UNSET
|
|
165
|
+
}
|
|
166
|
+
self._validate(entity_type, fields)
|
|
167
|
+
if 'roles' in fields:
|
|
168
|
+
fields['roles'] = tuple(fields['roles'])
|
|
169
|
+
if 'strategies' in fields:
|
|
170
|
+
fields['strategies'] = dict(fields['strategies'])
|
|
171
|
+
if 'public' in fields:
|
|
172
|
+
fields['public'] = frozenset(fields['public'])
|
|
173
|
+
if 'deployment_fields' in fields:
|
|
174
|
+
fields['deployment_fields'] = dict(fields['deployment_fields'])
|
|
175
|
+
for name in ('can_contain', 'contained_by'):
|
|
176
|
+
if fields.get(name) is not None:
|
|
177
|
+
fields[name] = tuple(fields[name])
|
|
178
|
+
self._defined[entity_type] = fields
|
|
179
|
+
self._described.clear()
|
|
180
|
+
|
|
181
|
+
def extend(
|
|
182
|
+
self,
|
|
183
|
+
entity_type: Type,
|
|
184
|
+
*,
|
|
185
|
+
roles: Sequence[Role] = (),
|
|
186
|
+
strategies: Optional[dict[type, Perm]] = None,
|
|
187
|
+
) -> None:
|
|
188
|
+
"""Add roles and strategies to a type another app defines. Role names
|
|
189
|
+
must start with the declaring app's id, because every app shares the
|
|
190
|
+
type. Strategies must be the declaring app's own; they join the
|
|
191
|
+
type's allowlist, and are how an app's strategy can run on (or
|
|
192
|
+
without a target, on) a type whose allowlist is closed."""
|
|
193
|
+
self._check_open()
|
|
194
|
+
strategies = dict(strategies or {})
|
|
195
|
+
app_id = self._declaring_app_id
|
|
196
|
+
if app_id and not self._owns(app_id, entity_type):
|
|
197
|
+
for role in roles:
|
|
198
|
+
if not role.name.startswith(f"{app_id}."):
|
|
199
|
+
raise ValueError(f"Role '{role.name}' must be named '{app_id}.<name>'")
|
|
200
|
+
if app_id and app_id != KERNEL_APP_ID:
|
|
201
|
+
for strategy in strategies:
|
|
202
|
+
if self.strategy_directory.owner_of(strategy) != app_id:
|
|
203
|
+
raise ValueError(
|
|
204
|
+
f"{strategy.__name__} belongs to another app; extend may only add the declaring app's strategies"
|
|
205
|
+
)
|
|
206
|
+
for strategy, perm in strategies.items():
|
|
207
|
+
if not isinstance(perm, Perm):
|
|
208
|
+
raise TypeError(f"{entity_type.__name__}: permission for {strategy.__name__} must be a Perm")
|
|
209
|
+
self._extended.setdefault(entity_type, []).extend((role, app_id) for role in roles)
|
|
210
|
+
self._extended_strategies.setdefault(entity_type, {}).update(strategies)
|
|
211
|
+
self._described.clear()
|
|
212
|
+
|
|
213
|
+
def declare_group(self, *, key: str, name: str) -> None:
|
|
214
|
+
"""A group seeded into every deployment that installs this app,
|
|
215
|
+
found by `key` (see docs/AUTHORIZATION_TECHNICAL_TDD.md,
|
|
216
|
+
Identity-based policy)."""
|
|
217
|
+
self._check_open()
|
|
218
|
+
app_id = self._declaring_app_id
|
|
219
|
+
if app_id and app_id != KERNEL_APP_ID and not key.startswith(f"{app_id}."):
|
|
220
|
+
raise ValueError(f"Group key '{key}' must be named '{app_id}.<name>'")
|
|
221
|
+
if key in self._declared_groups:
|
|
222
|
+
raise ValueError(f"Group '{key}' already declared")
|
|
223
|
+
self._declared_groups[key] = name
|
|
224
|
+
|
|
225
|
+
def declared_groups(self) -> dict[str, str]:
|
|
226
|
+
return dict(self._declared_groups)
|
|
227
|
+
|
|
228
|
+
def close(self) -> None:
|
|
229
|
+
"""Freeze the policy. Role names are checked here, once every app has
|
|
230
|
+
declared, so configurator order does not matter."""
|
|
231
|
+
for entity_type in set(self._defined) | set(self._extended):
|
|
232
|
+
names = [role.name for role in self.describe(entity_type).roles]
|
|
233
|
+
duplicates = sorted({name for name in names if names.count(name) > 1})
|
|
234
|
+
if duplicates:
|
|
235
|
+
raise ValueError(f"Roles declared twice for {entity_type.__name__}: {', '.join(duplicates)}")
|
|
236
|
+
self._closed = True
|
|
237
|
+
|
|
238
|
+
@property
|
|
239
|
+
def closed(self) -> bool:
|
|
240
|
+
return self._closed
|
|
241
|
+
|
|
242
|
+
def _owns(self, app_id: str, entity_type: Type) -> bool:
|
|
243
|
+
type_id = getattr(entity_type, '__dict__', {}).get('_graphcore_entity_type_id')
|
|
244
|
+
return type_id is None or type_id.startswith(f"{app_id}.")
|
|
245
|
+
|
|
246
|
+
def _check_owner(self, entity_type: Type) -> None:
|
|
247
|
+
app_id = self._declaring_app_id
|
|
248
|
+
if app_id and not self._owns(app_id, entity_type):
|
|
249
|
+
raise ValueError(
|
|
250
|
+
f"{entity_type.__name__} belongs to another app; only the app that registered a type "
|
|
251
|
+
"defines its policy (use extend to add roles)"
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
@staticmethod
|
|
255
|
+
def _validate(entity_type: Type, fields: dict) -> None:
|
|
256
|
+
for name in ('shareable', 'other_strategies', 'creatable'):
|
|
257
|
+
if name in fields and not isinstance(fields[name], bool):
|
|
258
|
+
raise TypeError(f"{entity_type.__name__}: {name} must be a bool")
|
|
259
|
+
for name in ('create', 'read', 'delete'):
|
|
260
|
+
if name in fields and not isinstance(fields[name], Perm):
|
|
261
|
+
raise TypeError(f"{entity_type.__name__}: {name} must be a Perm")
|
|
262
|
+
for name in ('can_contain', 'contained_by'):
|
|
263
|
+
if fields.get(name) is not None and not all(isinstance(cls, type) for cls in fields[name]):
|
|
264
|
+
raise TypeError(f"{entity_type.__name__}: {name} must be a list of types")
|
|
265
|
+
if fields.get('contained_by') is not None and not fields['contained_by']:
|
|
266
|
+
raise ValueError(
|
|
267
|
+
f"{entity_type.__name__}: contained_by=[] admits no parent; "
|
|
268
|
+
"use creatable=False for a type only kernel code creates"
|
|
269
|
+
)
|
|
270
|
+
if 'roles' in fields and not all(isinstance(role, Role) for role in fields['roles']):
|
|
271
|
+
raise TypeError(f"{entity_type.__name__}: roles must be Role instances")
|
|
272
|
+
if 'public' in fields and not all(isinstance(perm, Perm) for perm in fields['public']):
|
|
273
|
+
raise TypeError(f"{entity_type.__name__}: public must be Perm instances")
|
|
274
|
+
for field, perm in dict(fields.get('deployment_fields', {})).items():
|
|
275
|
+
if not isinstance(field, str) or not isinstance(perm, Perm):
|
|
276
|
+
raise TypeError(f"{entity_type.__name__}: deployment_fields maps field names to Perms")
|
|
277
|
+
if 'strategies' in fields:
|
|
278
|
+
for strategy, perm in dict(fields['strategies']).items():
|
|
279
|
+
if not isinstance(perm, Perm):
|
|
280
|
+
raise TypeError(f"{entity_type.__name__}: permission for {strategy.__name__} must be a Perm")
|
|
281
|
+
|
|
282
|
+
# --- reading ----------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
def describe(self, entity_type: Type) -> EffectivePolicy:
|
|
285
|
+
described = self._described.get(entity_type)
|
|
286
|
+
if described is None:
|
|
287
|
+
described = self._resolve(entity_type)
|
|
288
|
+
self._described[entity_type] = described
|
|
289
|
+
return described
|
|
290
|
+
|
|
291
|
+
def _resolve(self, entity_type: Type) -> EffectivePolicy:
|
|
292
|
+
mro = [cls for cls in getattr(entity_type, '__mro__', (entity_type,)) if cls in self._defined]
|
|
293
|
+
|
|
294
|
+
def nearest(name, default):
|
|
295
|
+
for cls in mro:
|
|
296
|
+
if name in self._defined[cls]:
|
|
297
|
+
return self._defined[cls][name]
|
|
298
|
+
return default
|
|
299
|
+
|
|
300
|
+
strategies: dict[type, Perm] = {}
|
|
301
|
+
deployment_fields: dict[str, Perm] = {}
|
|
302
|
+
for cls in reversed(mro):
|
|
303
|
+
strategies.update(self._defined[cls].get('strategies', {}))
|
|
304
|
+
deployment_fields.update(self._defined[cls].get('deployment_fields', {}))
|
|
305
|
+
|
|
306
|
+
allowed = None
|
|
307
|
+
for cls in mro:
|
|
308
|
+
if 'other_strategies' in self._defined[cls]:
|
|
309
|
+
if not self._defined[cls]['other_strategies']:
|
|
310
|
+
allowed = frozenset(self._defined[cls].get('strategies', {}))
|
|
311
|
+
break
|
|
312
|
+
|
|
313
|
+
roles = list(nearest('roles', DEFAULT_ROLES))
|
|
314
|
+
for cls in reversed(getattr(entity_type, '__mro__', (entity_type,))):
|
|
315
|
+
roles.extend(role for role, _ in self._extended.get(cls, ()))
|
|
316
|
+
extra = self._extended_strategies.get(cls, {})
|
|
317
|
+
strategies.update(extra)
|
|
318
|
+
if allowed is not None:
|
|
319
|
+
allowed |= frozenset(extra)
|
|
320
|
+
|
|
321
|
+
return EffectivePolicy(
|
|
322
|
+
shareable=nearest('shareable', False),
|
|
323
|
+
roles=tuple(roles),
|
|
324
|
+
strategies=MappingProxyType(strategies),
|
|
325
|
+
allowed_strategies=allowed,
|
|
326
|
+
create=nearest('create', Create()),
|
|
327
|
+
creatable=nearest('creatable', not self._is_principal(entity_type)),
|
|
328
|
+
public=nearest('public', frozenset()),
|
|
329
|
+
read=nearest('read', Read()),
|
|
330
|
+
delete=nearest('delete', Delete()),
|
|
331
|
+
can_contain=nearest('can_contain', None),
|
|
332
|
+
contained_by=nearest('contained_by', None),
|
|
333
|
+
deployment_fields=MappingProxyType(deployment_fields),
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
def _is_principal(self, entity_type: Type) -> bool:
|
|
337
|
+
type_id = getattr(entity_type, '__dict__', {}).get('_graphcore_entity_type_id')
|
|
338
|
+
return bool(self.entity_directory and type_id and self.entity_directory.is_principal(type_id))
|
|
339
|
+
|
|
340
|
+
def is_shareable(self, entity_type: Type) -> bool:
|
|
341
|
+
return self.describe(entity_type).shareable
|
|
342
|
+
|
|
343
|
+
def allowed_strategies(self, entity_type: Type) -> Optional[frozenset[type]]:
|
|
344
|
+
return self.describe(entity_type).allowed_strategies
|
|
345
|
+
|
|
346
|
+
def require_listed(self, entity_type: Type, strategy_cls: Type, action: str) -> None:
|
|
347
|
+
"""Raise `Forbidden` if `entity_type` has a closed allowlist without
|
|
348
|
+
`strategy_cls`; `action` names what was refused (`target`, `write`)."""
|
|
349
|
+
allowed = self.allowed_strategies(entity_type)
|
|
350
|
+
if allowed is None or strategy_cls in allowed:
|
|
351
|
+
return
|
|
352
|
+
strategy, name = strategy_cls.__name__, entity_type.__name__
|
|
353
|
+
raise Forbidden(
|
|
354
|
+
f"{strategy} may not {action} a {name}: it is not in {name}'s strategy allowlist "
|
|
355
|
+
f"(other_strategies=False). Add it to `strategies` in {name}'s policy to allow it."
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
def required_permission(self, entity_type: Type, strategy_cls: Type) -> Perm:
|
|
359
|
+
perm = self.describe(entity_type).strategies.get(strategy_cls)
|
|
360
|
+
if perm is not None:
|
|
361
|
+
return perm
|
|
362
|
+
if self.strategy_directory.is_read_only(strategy_cls):
|
|
363
|
+
return self.read_permission(entity_type)
|
|
364
|
+
return Write()
|
|
365
|
+
|
|
366
|
+
def available_roles(self, entity_type: Type) -> list[Role]:
|
|
367
|
+
return list(self.describe(entity_type).roles)
|
|
368
|
+
|
|
369
|
+
def type_public_perms(self, entity_type: Type) -> frozenset[Perm]:
|
|
370
|
+
return self.describe(entity_type).public
|
|
371
|
+
|
|
372
|
+
def create_permission(self, entity_type: Type) -> Perm:
|
|
373
|
+
return self.describe(entity_type).create
|
|
374
|
+
|
|
375
|
+
def is_creatable(self, entity_type: Type) -> bool:
|
|
376
|
+
return self.describe(entity_type).creatable
|
|
377
|
+
|
|
378
|
+
def read_permission(self, entity_type: Type) -> Perm:
|
|
379
|
+
return self.describe(entity_type).read
|
|
380
|
+
|
|
381
|
+
def delete_permission(self, entity_type: Type) -> Perm:
|
|
382
|
+
return self.describe(entity_type).delete
|
|
383
|
+
|
|
384
|
+
def can_contain(self, entity_type: Type) -> Optional[tuple[type, ...]]:
|
|
385
|
+
return self.describe(entity_type).can_contain
|
|
386
|
+
|
|
387
|
+
def contained_by(self, entity_type: Type) -> Optional[tuple[type, ...]]:
|
|
388
|
+
return self.describe(entity_type).contained_by
|
|
389
|
+
|
|
390
|
+
def deployment_fields(self, entity_type: Type) -> Mapping[str, Perm]:
|
|
391
|
+
return self.describe(entity_type).deployment_fields
|
|
392
|
+
|
|
393
|
+
def parent_type_ids_refusing(self, child_cls: Type) -> set[str]:
|
|
394
|
+
"""Registered type ids whose `can_contain` does not admit `child_cls`."""
|
|
395
|
+
refusing = set()
|
|
396
|
+
for type_id, entity_cls in self.entity_directory.get_all_entities().items():
|
|
397
|
+
allowed = self.can_contain(entity_cls)
|
|
398
|
+
if allowed is not None and not issubclass(child_cls, allowed):
|
|
399
|
+
refusing.add(type_id)
|
|
400
|
+
return refusing
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
DEFAULT_POLICY = AccessPolicy()
|
|
File without changes
|