Ir para o conteúdo

tempest_fastapi_sdk.privacy

Exportação e apagamento de dados do titular (LGPD art. 18, GDPR art. 15/17).

« Documentos e arquivos


privacy

Data-subject export and erasure (LGPD art. 18, GDPR art. 15/17).

Two halves, one per place personal data lives:

  • :class:SubjectGraph derives, from SQLAlchemy MetaData, the tables a delete of the subject's root row cascades to, exports one subject's rows without secret columns, and lists the foreign keys that would break erasure (:func:~tempest_fastapi_sdk.testing.assert_subject_graph_valid turns that into a CI guard);
  • :class:SubjectObjectStorage keeps every object of a subject under one prefix of an :class:~tempest_fastapi_sdk.storage.AsyncMinIOClient and erases the prefix in S3 batch deletes.

SubjectGraph needs only SQLAlchemy (base install). SubjectObjectStorage needs a client, which needs the [minio] extra; importing this package does not.

DEFAULT_SECRET_MARKERS module-attribute

DEFAULT_SECRET_MARKERS: tuple[str, ...] = ('hash', 'secret', 'password')

Substrings that mark a column as secret by name (case-insensitive).

A column whose name contains any of them (password_hash, totp_secret, api_key_hash) is left out of :meth:SubjectGraph.export. Mark a column explicitly with mapped_column(..., info={"secret": True}) or list it in secret_columns when the name says nothing.

SECRET_INFO_KEY module-attribute

SECRET_INFO_KEY: str = 'secret'

Key of Column.info that marks a column as secret when truthy.

SubjectGraph

SubjectGraph(
    metadata: MetaData,
    *,
    root: str | Table,
    retained: Mapping[str, str] | None = None,
    secret_columns: Mapping[str, Collection[str]] | None = None,
    secret_markers: Collection[str] = DEFAULT_SECRET_MARKERS,
    exclude_binary: bool = True,
    value_matches: Mapping[str, str] | None = None,
)

Cascade closure of a data subject, read from SQLAlchemy metadata.

Example:

>>> graph = SubjectGraph(Base.metadata, root="users")
>>> graph.tables()
['users', 'addresses', 'orders', 'order_items']
>>> graph.violations()
[]
>>> payload = await graph.export(session, user_id)
>>> payload["orders"][0]["total"]
'19.90'

Attributes:

Name Type Description
metadata MetaData

The metadata the graph was derived from.

root Table

The table whose primary key identifies the subject.

retained dict[str, str]

"table.column" of each SET NULL foreign key accepted into the closure, mapped to the reason the row outlives the subject.

secret_columns dict[str, frozenset[str]]

Extra columns per table left out of the export.

secret_markers tuple[str, ...]

Name substrings that mark a column as secret.

exclude_binary bool

Whether LargeBinary columns are left out of the export.

value_matches dict[str, str]

"table.column" of each column that identifies the subject by value, mapped to the key of the values mapping its value comes from.

Derive the closure from metadata.

Parameters:

Name Type Description Default
metadata MetaData

Metadata holding every table of the service (Base.metadata).

required
root str | Table

The subject's root table, by name or object. Its single-column primary key is the subject id.

required
retained Mapping[str, str] | None

Foreign keys that may point into the closure with ON DELETE SET NULL because the row is kept after erasure (an invoice the tax law requires, a message in a shared thread). Keys are "table.column" ("table.col_a,col_b" for a composite key), values are the reason. Every entry must name an existing nullable SET NULL key into the closure, or it is reported by :meth:violations.

None
secret_columns Mapping[str, Collection[str]] | None

Columns to leave out of the export per table name, beyond the ones caught by secret_markers and info={"secret": True}.

None
secret_markers Collection[str]

Case-insensitive substrings of a column name that mark it as secret. Defaults to :data:DEFAULT_SECRET_MARKERS.

DEFAULT_SECRET_MARKERS
exclude_binary bool

Leave LargeBinary columns (and its subclasses) out of the export. A queue payload or a model blob is not data the subject can read, and in base64 it is only volume. False keeps them, base64-encoded.

True
value_matches Mapping[str, str] | None

Columns that identify the subject by value rather than by foreign key — an invite sent to the subject keeps their e-mail in invites.to_email while its key points at the sender. Keys are "table.column" of a closure table, values are the key of the values mapping that :meth:condition, :meth:export, :meth:count and :meth:erase receive ({"invites.to_email": "email"} with values={"email": "ana@example.com"}). An entry outside the closure or naming a missing column is reported by :meth:violations.

None

Raises:

Type Description
KeyError

When root names a table missing from metadata.

ValueError

When the root table does not have exactly one primary-key column.

tables

tables() -> list[str]

Return the tables a delete of the root row reaches.

Returns:

Type Description
list[str]

list[str]: Table names, root first, breadth-first from it.

violations

violations() -> list[str]

List every foreign key that would break erasure of a subject.

A foreign key whose target table is in the closure must cascade, or be a nullable SET NULL key listed in retained. Anything else (NO ACTION, RESTRICT, an unlisted SET NULL) makes the root delete fail or leaves the subject's id behind. Stale retained entries are reported too, so the allowlist cannot rot.

Returns:

Type Description
list[str]

list[str]: One human-readable line per problem, sorted. Empty

list[str]

list when the schema supports erasure.

is_secret

is_secret(table: Table, column_name: str) -> bool

Tell whether a column is left out of the export.

Parameters:

Name Type Description Default
table Table

The table owning the column.

required
column_name str

The column name.

required

Returns:

Name Type Description
bool bool

True when the column is listed in secret_columns,

bool

carries info={"secret": True}, its name contains one of

bool

secret_markers, or — under exclude_binary — its type is

bool

LargeBinary.

exported_columns

exported_columns(table: str | Table) -> list[str]

Return the columns of a closure table that the export includes.

Parameters:

Name Type Description Default
table str | Table

A table of the closure, by name or object.

required

Returns:

Type Description
list[str]

list[str]: Column names in declaration order, secrets removed.

Raises:

Type Description
KeyError

When the table is not part of the closure.

condition

condition(
    table: str | Table, subject_id: object, *, values: Mapping[str, Any] | None = None
) -> ColumnElement[bool]

Build the WHERE clause selecting one subject's rows of a table.

The root matches on its primary key. Any other table matches when one of its cascading foreign keys points at a row of a closure table that itself belongs to the subject, as a nested IN (SELECT ...). A row reachable only through a cycle back to its own table (a reply to a reply, by another subject) is not considered the subject's. A table listed in value_matches also matches when its column equals the given value, and so do the rows that cascade from it.

Parameters:

Name Type Description Default
table str | Table

A table of the closure.

required
subject_id object

The value of the root's primary key.

required
values Mapping[str, Any] | None

The subject's identifying values, by the keys value_matches names. A key left out (or None) adds no match.

None

Returns:

Type Description
ColumnElement[bool]

ColumnElement[bool]: The clause, usable in select,

ColumnElement[bool]

update or delete.

Raises:

Type Description
KeyError

When the table is not part of the closure.

export async

export(
    session: AsyncSession,
    subject_id: object,
    *,
    values: Mapping[str, Any] | None = None,
) -> dict[str, list[dict[str, Any]]]

Read every row of the closure that belongs to one subject.

Parameters:

Name Type Description Default
session AsyncSession

An open async session.

required
subject_id object

The value of the root's primary key.

required
values Mapping[str, Any] | None

The subject's identifying values, for the tables in value_matches.

None

Returns:

Type Description
dict[str, list[dict[str, Any]]]

dict[str, list[dict[str, Any]]]: Every closure table name (in

dict[str, list[dict[str, Any]]]

meth:tables order) mapped to its rows, each row a dict of the

dict[str, list[dict[str, Any]]]

meth:exported_columns with JSON-serialisable values. A table

dict[str, list[dict[str, Any]]]

with no rows maps to an empty list; an unknown subject yields

dict[str, list[dict[str, Any]]]

empty lists throughout.

count async

count(
    session: AsyncSession,
    subject_id: object,
    *,
    values: Mapping[str, Any] | None = None,
) -> dict[str, int]

Count one subject's rows per closure table.

Run it after deleting the root row to prove the erasure reached every table: every count must be 0. Pass the same values as the export — without them, a row the subject owns only by value is not counted, and the proof says 0 with it still stored.

Parameters:

Name Type Description Default
session AsyncSession

An open async session.

required
subject_id object

The value of the root's primary key.

required
values Mapping[str, Any] | None

The subject's identifying values, for the tables in value_matches.

None

Returns:

Type Description
dict[str, int]

dict[str, int]: Every closure table name mapped to its row

dict[str, int]

count for the subject.

erase async

erase(
    session: AsyncSession,
    subject_id: object,
    *,
    values: Mapping[str, Any] | None = None,
) -> dict[str, int]

Delete one subject's rows and return the proof.

Deletes the rows each value_matches entry selects (the database cascades from them), then the root row (the database cascades the rest of the closure), flushes, and returns :meth:count — which should be 0 everywhere. It does not commit: the caller decides, and can roll back when the proof is not clean.

Parameters:

Name Type Description Default
session AsyncSession

An open async session. The ON DELETE rules must be enforced by the connection (on SQLite, with foreign keys on, which the SDK's engines turn on).

required
subject_id object

The value of the root's primary key.

required
values Mapping[str, Any] | None

The subject's identifying values, for the tables in value_matches.

None

Returns:

Type Description
dict[str, int]

dict[str, int]: :meth:count after the deletes.

SubjectErasureError

SubjectErasureError(subject_id: str, errors: list[ObjectDeleteError])

Bases: Exception

Raised when the store refuses to delete some of a subject's objects.

Attributes:

Name Type Description
subject_id str

The subject whose prefix was being erased.

errors list[ObjectDeleteError]

One entry per key that was not deleted, with the store's error code and message.

Build the error.

Parameters:

Name Type Description Default
subject_id str

The subject whose prefix was being erased.

required
errors list[ObjectDeleteError]

The keys the store refused.

required

SubjectObjectStorage

SubjectObjectStorage(
    client: SubjectStorageClient, *, prefix: str = "subjects", bucket: str | None = None
)

Store objects under a per-subject prefix and erase them in batch.

Example:

>>> storage = SubjectObjectStorage(client, prefix="users")
>>> await storage.put(user_id, "avatar.png", data, content_type="image/png")
'users/42/avatar.png'
>>> await storage.presign(user_id, "avatar.png")
'https://...'
>>> await storage.presign_put(user_id, "upload.jpg")
'https://...'
>>> await storage.read(user_id, "upload.jpg", max_bytes=1_048_577)
b'...'
>>> await storage.delete_all(user_id)
1

Attributes:

Name Type Description
client SubjectStorageClient

The underlying object-storage client — an :class:~tempest_fastapi_sdk.storage.AsyncMinIOClient, or :class:~tempest_fastapi_sdk.testing.fakes.FakeObjectStorageClient in a test.

prefix str

Root prefix every subject lives under, without surrounding slashes.

bucket str | None

Bucket override; None uses the client's default_bucket.

Wrap client.

Parameters:

Name Type Description Default
client SubjectStorageClient

The object-storage client.

required
prefix str

Root prefix every subject lives under. Leading and trailing slashes are stripped; inner slashes are allowed ("tenants/acme/users"). Default "subjects".

'subjects'
bucket str | None

Bucket for every operation; None uses the client's default_bucket.

None

Raises:

Type Description
ValueError

When prefix is empty after stripping slashes or holds an empty, . or .. segment.

subject_prefix

subject_prefix(subject_id: object) -> str

Return the key prefix holding every object of a subject.

Parameters:

Name Type Description Default
subject_id object

The subject id; converted with str().

required

Returns:

Name Type Description
str str

"<prefix>/<subject_id>/", trailing slash included.

Raises:

Type Description
ValueError

When str(subject_id) is empty, ./.., or holds a /.

key

key(subject_id: object, name: str) -> str

Return the full object key of one subject's object.

Parameters:

Name Type Description Default
subject_id object

The subject id; converted with str().

required
name str

Object name relative to the subject's prefix. Inner slashes are allowed ("exports/2026.zip").

required

Returns:

Name Type Description
str str

"<prefix>/<subject_id>/<name>".

Raises:

Type Description
ValueError

When the subject id is not a valid segment, or name is empty, starts with /, or holds an empty, . or .. segment — anything that could step outside the subject's prefix.

put async

put(
    subject_id: object,
    name: str,
    data: bytes | BinaryIO,
    *,
    content_type: str = "application/octet-stream",
    metadata: dict[str, str] | None = None,
    length: int | None = None,
) -> str

Upload an object under the subject's prefix.

Parameters:

Name Type Description Default
subject_id object

The subject id.

required
name str

Object name relative to the subject's prefix.

required
data bytes | BinaryIO

Payload; file-like data needs length (-1 for unknown-length multipart).

required
content_type str

MIME type.

'application/octet-stream'
metadata dict[str, str] | None

User metadata.

None
length int | None

Payload size for file-like data.

None

Returns:

Name Type Description
str str

The full object key written.

Raises:

Type Description
ValueError

When the subject id or name is invalid, or file-like data omits length.

S3Error

When the upload fails.

presign async

presign(
    subject_id: object,
    name: str,
    *,
    expires: timedelta = timedelta(hours=1),
    filename: str | None = None,
    media_type: str | None = None,
    as_attachment: bool | None = None,
) -> str

Generate a temporary download URL for one subject's object.

Pass media_type with the type the server checked — from :meth:stat and the bytes, not the uploader's declaration — and the link answers with it: S3 signs it as a response-content-type override, the local backend binds it into its signature.

Parameters:

Name Type Description Default
subject_id object

The subject id.

required
name str

Object name relative to the subject's prefix.

required
expires timedelta

URL lifetime; at most 7 days.

timedelta(hours=1)
filename str | None

Name presented to the client.

None
media_type str | None

Content-Type the link answers with, a bare type/subtype.

None
as_attachment bool | None

True forces a download; False asks for inline, granted only to inline-safe types.

None

Returns:

Name Type Description
str str

Presigned GET URL.

Raises:

Type Description
ValueError

When the subject id or name is invalid, or media_type is not a bare type/subtype.

presign_put async

presign_put(
    subject_id: object, name: str, *, expires: timedelta = timedelta(minutes=15)
) -> str

Generate a temporary upload URL for one subject's object.

The client PUTs the bytes straight to the store, so they never cross the API process. The URL only reaches key(subject_id, name): the subject prefix is fixed by the server when it signs, never by the uploader. Nothing about the payload is signed — size and content type are whatever the client sends — so verify the object with :meth:stat and :meth:read before trusting it, or issue :meth:presign_post, whose size and type the store enforces.

Parameters:

Name Type Description Default
subject_id object

The subject id.

required
name str

Object name relative to the subject's prefix.

required
expires timedelta

URL lifetime; at most 7 days. Default 15 minutes, the same as :meth:~tempest_fastapi_sdk.storage.AsyncMinIOClient.presigned_put_url.

timedelta(minutes=15)

Returns:

Name Type Description
str str

Presigned PUT URL.

Raises:

Type Description
ValueError

When the subject id or name is invalid.

IntegrationDisabledException

When the client was built with enabled=False.

presign_post async

presign_post(
    subject_id: object,
    name: str,
    *,
    max_bytes: int,
    content_type: str | None = None,
    min_bytes: int = 0,
    expires: timedelta = timedelta(minutes=15),
) -> PresignedPost

Generate a form upload for one subject's object, capped in size.

The store refuses a file outside [min_bytes, max_bytes], another key and, when content_type is given, another type — S3 through the POST policy conditions, the local backend through its route. The cap is enforced before the bytes are stored, which :meth:presign_put cannot do. Still read the object before trusting its content: the declared type is not the bytes.

Parameters:

Name Type Description Default
subject_id object

The subject id.

required
name str

Object name relative to the subject's prefix.

required
max_bytes int

Largest accepted file.

required
content_type str | None

The only Content-Type accepted. None leaves it free.

None
min_bytes int

Smallest accepted file. Default 0.

0
expires timedelta

Lifetime; at most 7 days.

timedelta(minutes=15)

Returns:

Name Type Description
PresignedPost PresignedPost

The URL, the form fields to send before the file,

PresignedPost

and the cap.

Raises:

Type Description
ValueError

When the subject id or name is invalid, or the limits or content_type are invalid.

IntegrationDisabledException

When the client was built with enabled=False.

stat async

stat(subject_id: object, name: str) -> ObjectStat

Fetch one subject's object metadata without downloading it.

Parameters:

Name Type Description Default
subject_id object

The subject id.

required
name str

Object name relative to the subject's prefix.

required

Returns:

Name Type Description
ObjectStat ObjectStat

Size, content type, ETag and user metadata, as the

ObjectStat

store reports them.

Raises:

Type Description
ValueError

When the subject id or name is invalid.

S3Error

When the object is missing or the request fails; propagated unchanged from the client (FakeObjectStorageClient raises :class:FileNotFoundError instead).

IntegrationDisabledException

When the client was built with enabled=False.

read async

read(subject_id: object, name: str, *, max_bytes: int | None = None) -> bytes

Read one subject's object into memory, optionally capped.

With max_bytes, only the first max_bytes bytes are requested from the store (a Range read through :meth:~tempest_fastapi_sdk.storage.AsyncMinIOClient.stream_object), and reading stops there even if the store answers with more. An object that was swapped for a larger one after a :meth:stat never enters memory whole.

To detect "too large", pass limit + 1 and compare the length: len(data) > limit means the object exceeds limit, without reading the rest of it.

Parameters:

Name Type Description Default
subject_id object

The subject id.

required
name str

Object name relative to the subject's prefix.

required
max_bytes int | None

Read at most this many bytes. None (default) reads the whole object.

None

Returns:

Name Type Description
bytes bytes

The object's bytes, or its first max_bytes bytes.

Raises:

Type Description
ValueError

When the subject id or name is invalid, or max_bytes is not positive.

S3Error

When the object is missing or the request fails; propagated unchanged from the client (FakeObjectStorageClient raises :class:FileNotFoundError instead).

IntegrationDisabledException

When the client was built with enabled=False.

names async

names(subject_id: object) -> list[str]

List every object name of a subject.

Parameters:

Name Type Description Default
subject_id object

The subject id.

required

Returns:

Type Description
list[str]

list[str]: Names relative to the subject's prefix, sorted. Empty

list[str]

list when the subject has no objects.

Raises:

Type Description
ValueError

When the subject id is invalid.

delete async

delete(subject_id: object, name: str) -> None

Delete one object of a subject.

Parameters:

Name Type Description Default
subject_id object

The subject id.

required
name str

Object name relative to the subject's prefix.

required

Raises:

Type Description
ValueError

When the subject id or name is invalid.

delete_all async

delete_all(subject_id: object) -> int

Erase every object under the subject's prefix.

Lists the prefix and removes the keys with :meth:~tempest_fastapi_sdk.storage.AsyncMinIOClient.remove_objects (one S3 DeleteObjects request per 1000 keys). Objects of other subjects are never listed, so never deleted. Calling it again is a no-op that returns 0.

Parameters:

Name Type Description Default
subject_id object

The subject id.

required

Returns:

Name Type Description
int int

Number of objects deleted.

Raises:

Type Description
ValueError

When the subject id is invalid.

SubjectErasureError

When the store refused to delete some keys; the others are deleted.

SubjectStorageClient

Bases: Protocol

The object-storage calls :class:SubjectObjectStorage makes.

:class:~tempest_fastapi_sdk.storage.AsyncMinIOClient satisfies it, and so does :class:~tempest_fastapi_sdk.testing.fakes.FakeObjectStorageClient, which is what lets a test build the storage without MinIO. The signatures are AsyncMinIOClient's, minus the keyword arguments the storage never passes.

put_object async

put_object(
    key: str,
    data: bytes | BinaryIO,
    *,
    bucket: str | None = None,
    content_type: str = "application/octet-stream",
    metadata: dict[str, str] | None = None,
    length: int | None = None,
) -> str

Upload one object.

Parameters:

Name Type Description Default
key str

Object key.

required
data bytes | BinaryIO

The payload.

required
bucket str | None

Override target bucket.

None
content_type str

MIME type stored with the object.

'application/octet-stream'
metadata dict[str, str] | None

User metadata.

None
length int | None

Payload size, when data is a stream.

None

Returns:

Name Type Description
str str

The object's ETag.

presigned_get_url async

presigned_get_url(
    key: str,
    *,
    bucket: str | None = None,
    expires: timedelta = timedelta(hours=1),
    filename: str | None = None,
    media_type: str | None = None,
    as_attachment: bool | None = None,
) -> str

Generate a temporary download URL.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Override source bucket.

None
expires timedelta

URL lifetime.

timedelta(hours=1)
filename str | None

Name presented to the client, signed in.

None
media_type str | None

Content-Type the link answers with, signed in.

None
as_attachment bool | None

Download or inline, signed in.

None

Returns:

Name Type Description
str str

The presigned URL.

presigned_put_url async

presigned_put_url(
    key: str, *, bucket: str | None = None, expires: timedelta = timedelta(minutes=15)
) -> str

Generate a temporary upload URL.

Parameters:

Name Type Description Default
key str

Destination object key.

required
bucket str | None

Override target bucket.

None
expires timedelta

URL lifetime.

timedelta(minutes=15)

Returns:

Name Type Description
str str

The presigned URL accepting a PUT.

presigned_post_policy async

presigned_post_policy(
    key: str,
    *,
    max_bytes: int,
    content_type: str | None = None,
    min_bytes: int = 0,
    bucket: str | None = None,
    expires: timedelta = timedelta(minutes=15),
) -> PresignedPost

Generate a form upload capped at max_bytes.

Parameters:

Name Type Description Default
key str

Destination object key.

required
max_bytes int

Largest accepted file.

required
content_type str | None

The only Content-Type accepted.

None
min_bytes int

Smallest accepted file.

0
bucket str | None

Override target bucket.

None
expires timedelta

Lifetime.

timedelta(minutes=15)

Returns:

Name Type Description
PresignedPost PresignedPost

URL, form fields and cap.

stat_object async

stat_object(key: str, *, bucket: str | None = None) -> ObjectStat

Fetch an object's metadata without downloading it.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Override source bucket.

None

Returns:

Name Type Description
ObjectStat ObjectStat

Size, content type, ETag and user metadata.

stream_object async

stream_object(
    key: str,
    *,
    bucket: str | None = None,
    chunk_size: int = 64 * 1024,
    offset: int = 0,
    length: int | None = None,
) -> AsyncIterator[bytes]

Open an object, or one byte range of it, as a chunk stream.

Same parameters as :class:~tempest_fastapi_sdk.storage.DownloadableStore, so a client that satisfies this protocol can also be served by :func:~tempest_fastapi_sdk.storage.object_download_response.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Override source bucket.

None
chunk_size int

Bytes per chunk.

64 * 1024
offset int

First byte to read.

0
length int | None

How many bytes to read from offset; None reads to the end.

None

Returns:

Type Description
AsyncIterator[bytes]

AsyncIterator[bytes]: The chunks, in order.

list_objects async

list_objects(
    prefix: str = "", *, bucket: str | None = None, recursive: bool = True
) -> list[str]

List object keys under prefix.

Parameters:

Name Type Description Default
prefix str

Prefix filter.

''
bucket str | None

Override source bucket.

None
recursive bool

Descend into "subdirectories".

True

Returns:

Type Description
list[str]

list[str]: The matching keys.

remove_object async

remove_object(
    key: str, *, bucket: str | None = None, version_id: str | None = None
) -> None

Delete one object.

Parameters:

Name Type Description Default
key str

Object key.

required
bucket str | None

Override target bucket.

None
version_id str | None

Version to delete, on a versioned bucket.

None

remove_objects async

remove_objects(
    keys: Iterable[str], *, bucket: str | None = None
) -> list[ObjectDeleteError]

Delete many objects in batch.

Parameters:

Name Type Description Default
keys Iterable[str]

Object keys.

required
bucket str | None

Override target bucket.

None

Returns:

Type Description
list[ObjectDeleteError]

list[ObjectDeleteError]: The keys the store refused to delete.