NetAuth for Python

A NetAuth client library for Python.

To install: pip install netauth

Usage

This library centers around the NetAuth object:

na = netauth.NetAuth("netauth.example.org")

try:
    resp = na.system_status()
    print(resp)
except netauth.error.NetAuthRpcError as e:
    print(f"Request failed: {e}")

na.close()

NetAuth can also be used as a context manager and be initialized from a NetAuth configuration file:

with netauth.NetAuth.with_config(Path("/etc/netauth/config.toml")) as na:
    try:
        resp = na.system_status()
        print(resp)
    except netauth.error.NetAuthRpcError as e:
        print(f"Request failed: {e}")

For interactive or dynamic applications, operations that require authentication can use a callback to retrieve the user’s secret:

def secret_cb() -> str:
    return getpass(prompt="Secret: ")

with netauth.NetAuth("netauth.example.org", entity="demo", secret=secret_cb) as na:
    try:
        na.entity_kv_add("demo", "foo", ["bar", "baz"])
    except error.NetAuthRpcError as e:
        print(f"Request failed: {e}")

API

class netauth.NetAuth(server, port=1729, *, master=None, entity=None, secret=None, token_cache=None, client_name=None, service_name=None, cert=None, insecure=False)

Creates a new NetAuth client, connected and ready to use. If called as a context manager, the connection will automatically be closed upon exit.

Parameters:
  • server (str) – server to connect to

  • port (int) – port to connect to (default: 1729)

  • master (str | None) – the controller server in a NetAuth cluster (default: server)

  • entity (str | None) – the entity to perform authenticated operations as

  • secret (str | Callable[[], str] | None) – entity’s secret, or a callback for retrieving the entity’s secret

  • token_cache (TokenCache | None) – a TokenCache to store tokens in. If not specified, uses MemoryTokenCache.

  • client_name (str | None) – value to identify the client by (default: hostname)

  • service_name (str | None) – value to identify the application or service by (default: "netauth-python")

  • cert (Path | bytes | None) – TLS certificate to use (path to a PEM-encoded certificate, byte string of the PEM-encoded certificate itself, or None (default) to retrieve them from the default location chosen by the gRPC runtime)

  • insecure (bool) – disable TLS (default: False)

Raises:

NetAuthException – if server is not set

classmethod with_config(path, **kwargs)

Creates a new NetAuth client, connected and ready to use, from a NetAuth configuration file. This should be a TOML file with the same format as the NetAuth commandline utility’s configuration.

Accepts the same arguments as __init__ as keyword arguments. If specified, they will override values from the configuration.

Parameters:

path (Path) – path to the configuration file

close()

Close the underlying gRPC connection. Called automatically when the client object is deleted or, when using a context manager, the context is left.

entity_create(id, secret, number=-1)

Create a new entity.

Parameters:
  • id (str) – the new entity’s ID. Must be unique.

  • secret (str) – the new entity’s secret.

  • number (int) – the new entity’s number. Strongly recommended to be unique. If not provided, the next valid number will be selected and assigned.

Raises:
entity_update(id, meta)

Update the generic metadata on an existing entity.

Parameters:
  • id (str) – the entity’s ID

  • meta (EntityMeta) – the new metadata values

Raises:
entity_info(id)

Returns information about an entity. Does not require authentication.

Parameters:

id (str) – the entity’s ID

Raises:
Return type:

Entity | None

Returns:

the entity or None if not found

Searches all entities. Does not require authentication.

Parameters:

expr (str) – expression to search for

Raises:
Return type:

list[Entity]

Returns:

list of entities that match the search criteria

entity_untyped_meta(id, action, key, value='')

Perform operations on the untyped key-value store on an entity. Read operations do not require authentication.

Parameters:
  • id (str) – target entity ID

  • action (Action) – action to perform (Upsert, Read, ClearFuzzy, or ClearExact)

  • key (str) – key to read from or write to. If '*', operate on all keys.

  • value (str) – value to write, if writing

Raises:
Return type:

dict[str, list[str]] | None

Returns:

a dictionary of the requested keys and values if reading, nothing if writing or clearing

entity_kv_add(id, key, values)

Add a key to the specified entity. The key must not already exist. Value order will be preserved.

Parameters:
  • id (str) – target entity ID

  • key (str) – the key to add

  • values (list[str]) – the values to add

Raises:
entity_kv_get(id, key)

Returns values for the requested key if it exists.

Parameters:
  • id (str) – target entity ID

  • key (str) – the key to retrieve. If '*', get all keys.

Raises:
Return type:

dict[str, list[str]]

Returns:

the key-value mapping requested

entity_kv_del(id, key)

Delete a key from an entity.

Parameters:
  • id (str) – target entity ID

  • key (str) – the key to delete

Raises:
entity_kv_replace(id, key, values)

Replace a key for the specified entity. The key must already exist. Value order will be preserved.

Parameters:
  • id (str) – target entity ID

  • key (str) – the key to replace

  • values (list[str]) – the values to add

Raises:
entity_keys(id, action, kind, key)

Read, write, or drop public keys stored on an entity. Does not require authentication.

Parameters:
  • id (str) – target entity ID

  • action (Action) – action to perform (Add, Drop, or Read)

  • kind (str) – type of key. If '*', operate on all key types.

  • key (str) – key value

Raises:
Return type:

dict[str, list[str]] | None

Returns:

a dictionary of the requested keys and values if reading, nothing if writing or clearing

entity_destroy(id)

Permanently remove an entity from the server.This is not recommended and should not be done without good reason. The best practice is to instead have a group that defunct entities get moved to and then locked. This will prevent authentication, while maintaining integrity of the backing tree. This function does not maintain referential integrity, so be careful about removing the last standing admin of a particular type.

Parameters:

id (str) – target entity ID

Raises:
entity_lock(id)

Sets the lock bit on the target entity. Prevents authentication from proceeding even if correct authentication information is provided.

Parameters:

id (str) – target entity ID

Raises:
entity_unlock(id)

Unsets the lock bit on the target entity.

Parameters:

id (str) – target entity ID

Raises:
entity_groups(id)

Retrieves the effective group memberships of the target entity.

Parameters:

id (str) – target entity ID

Raises:
Return type:

list[Group]

auth_entity(id, secret)

Perform authentication for an entity. Does not acquire a token.

Parameters:
  • id (str) – target entity ID

  • secret (str) – target entity’s secret

Raises:
auth_get_token(id, secret)

Perform authentication for an entity and acquire a token if successful. This token can be used to authenticate future requests.

Parameters:
  • id (str) – target entity ID

  • secret (str) – target entity’s secret

Raises:
Return type:

str

Returns:

token, if successful

auth_validate_token(token)

Perform server-side validation of a token.

Parameters:

token (str) – token to check

Raises:
auth_change_secret(id, secret, old_secret=None)

Change the secret for an entity. If the entity is changing its own secret, the old secret should be provided. If an administrator is changing the secret, the request must be authenticated with a token.

Parameters:
  • id (str) – target entity ID

  • secret (str) – target entity’s new secret

  • old_secret (str | None) – target entity’s current secret, if needed

Raises:
group_create(name, display_name, managed_by=None, number=-1)

Create a new group.

Parameters:
  • name (str) – new group’s name. Must be unique.

  • display_name (str) – the new group’s display name.

  • managed_by (str | None) – the name of a group that manages the new group

  • number (int) – the new group’s number. Strongly recommended to be unique. If not provided, the next valid number will be selected and assigned.

Raises:
group_update(group)

Update group information. Fields that cannot be rewritten will be ignored.

Parameters:

group (Group) – new group information

Raises:
group_info(name)

Returns information about a group. Does not require authentication.

Parameters:

name (str) – target group’s name

Raises:
Return type:

tuple[Group, list[Group]] | None

Returns:

a tuple of the group and its managed groups, if found

group_untyped_meta(name, action, key, value='')

Perform operations on the untyped key-value store on a group. Read operations do not require authentication.

Parameters:
  • name (str) – target group’s name

  • action (Action) – action to perform (Upsert, Read, ClearFuzzy, or ClearExact)

  • key (str) – key to read from or write to. If '*', operate on all keys.

  • value (str) – value to write, if writing

Raises:
Return type:

dict[str, list[str]] | None

Returns:

a dictionary of the requested keys and values if reading, nothing if writing or clearing

group_kv_add(name, key, values)

Add a key to the specified group. The key must not already exist. Value order will be preserved.

Parameters:
  • name (str) – target group name

  • key (str) – the key to add

  • values (list[str]) – the values to add

Raises:
group_kv_get(name, key)

Returns values for the requested key if it exists.

Parameters:
  • name (str) – target group name

  • key (str) – the key to retrieve. If '*', get all keys.

Raises:
Return type:

dict[str, list[str]]

Returns:

the key-value mapping requested

group_kv_del(name, key)

Delete a key from a group.

Parameters:
  • name (str) – target group name

  • key (str) – the key to delete

Raises:
group_kv_replace(name, key, values)

Replace a key for the specified group. The key must already exist. Value order will be preserved.

Parameters:
  • name (str) – target group name

  • key (str) – the key to replace

  • values (list[str]) – the values to add

Raises:
group_update_rules(name, action, target)

Manage rules on groups. Rules can an transparently include other groups, recursively remove members, or reset the behavior of a group to default.

Parameters:
  • name (str) – group name

  • action (RuleAction) – type of rule action to take

  • target (str) – target group name

Raises:
group_add_member(group, entity)

Add a member to a group.

Parameters:
  • group (str) – target group name

  • entity (str) – ID of the entity to add

Raises:
group_del_member(group, entity)

Remove a member from a group.

Parameters:
  • group (str) – target group name

  • entity (str) – ID of the entity to remove

Raises:
group_destroy(name)

Permanently remove a group from the server. This is not recommended as NetAuth does not perform internal referential integrity checks, so it is possible to remove a group that has rules pointing at it or otherwise create cycles in the graph. The best practices are to keep groups forever. They’re cheap and as long as they’re not queried they don’t represent additional load.

Parameters:

name (str) – target group name

Raises:
group_members(name)

Returns the membership of a group, include any alterations from rules.

Parameters:

name (str) – the name of the group

Raises:
Return type:

list[Entity]

Returns:

the group members

Searches all groups. Does not require authentication.

Parameters:

expr (str) – expression to search for

Raises:
Return type:

list[Group]

Returns:

list of groups that match the search criteria

system_capabilities(target, action, capability, direct=False)

Modify capabilities within the server.

Parameters:
  • target (str) – name of group or ID of entity to set the capability on

  • action (Action) – action to perform (Add or Drop)

  • capability (Capability) – capability to add or drop

  • direct (bool) – set the capability on an entity target (discouraged, default: False)

Raises:
system_ping()

Pings the server. Returns successfully if the server is healthy.

Raises:

NetAuthRpcError – if a gRPC error occurred

system_status()

Returns detailed status information about the server.

Raises:

NetAuthRpcError – if a gRPC error occurred

Return type:

ServerStatus

Returns:

server status information

Data Types

class netauth.EntityMeta(primary_group=None, gecos=None, legal_name=None, display_name=None, home=None, shell=None, graphical_shell=None, badge_number=None, locked=False, groups=<factory>, capabilities=<factory>, keys=<factory>, untyped_meta=<factory>, kv=<factory>)

Entity metadata

class netauth.Entity(id=None, number=None, secret=None, meta=None)

Entity information

class netauth.Group(name=None, display_name=None, number=None, managed_by=None, capabilities=<factory>, expansions=<factory>, untyped_meta=<factory>, kv=<factory>)

Group information

class netauth.v2.SubSystemStatus(name=None, ok=True, fault_message=None)

Subsystem status information

class netauth.v2.ServerStatus(system_ok=False, first_failure=None, subsystems=<factory>)

Server status information

Enumerations

enum netauth.Capability(value)

System capabilities

Valid values are as follows:

GlobalRoot = <Capability.GlobalRoot: 0>
CreateEntity = <Capability.CreateEntity: 10>
DestroyEntity = <Capability.DestroyEntity: 11>
ModifyEntityMeta = <Capability.ModifyEntityMeta: 12>
ModifyEntityKeys = <Capability.ModifyEntityKeys: 13>
ChangeEntitySecret = <Capability.ChangeEntitySecret: 14>
LockEntity = <Capability.LockEntity: 15>
UnlockEntity = <Capability.UnlockEntity: 16>
CreateGroup = <Capability.CreateGroup: 20>
DestroyGroup = <Capability.DestroyGroup: 21>
ModifyGroupMeta = <Capability.ModifyGroupMeta: 22>
ModifyGroupMembers = <Capability.ModifyGroupMembers: 23>
enum netauth.ExpansionMode(value)

Group expansion modes

Valid values are as follows:

Include = <ExpansionMode.Include: 1>
Exclude = <ExpansionMode.Exclude: 2>
Drop = <ExpansionMode.Drop: 99>
enum netauth.v2.Action(value)

Actions available for various operations

Valid values are as follows:

Add = <Action.Add: 1>
Drop = <Action.Drop: 2>
Upsert = <Action.Upsert: 3>
ClearExact = <Action.ClearExact: 4>
ClearFuzzy = <Action.ClearFuzzy: 5>
Read = <Action.Read: 6>
enum netauth.v2.RuleAction(value)

Actions available for group rule operations

Valid values are as follows:

Include = <RuleAction.Include: 1>
Exclude = <RuleAction.Exclude: 2>
RemoveRule = <RuleAction.RemoveRule: 99>

Token Cache

class netauth.cache.TokenCache

Base class for token caches

abstract put(entity, token)

Add or set the token for an entity

Parameters:
  • entity (str) – token’s owner

  • token (str) – token to store

abstract get(entity)

Get the token for an entity

Parameters:

entity (str) – token’s owner

Return type:

str | None

Returns:

token, or None if not in cache

abstract delete(entity)

Remove the token for an entity

Parameters:

entity (str) – token’s owner

class netauth.cache.FSTokenCache

Filesystem-backed token cache. Stores tokens in files named {entity}.nt in the OS’s temporary files directory.

Useful for short-running applications and prefetching tokens.

put(entity, token)

Add or set the token for an entity

Parameters:
  • entity (str) – token’s owner

  • token (str) – token to store

get(entity)

Get the token for an entity

Parameters:

entity (str) – token’s owner

Return type:

str | None

Returns:

token, or None if not in cache

delete(entity)

Remove the token for an entity

Parameters:

entity (str) – token’s owner

class netauth.cache.MemoryTokenCache

Memory-backed token cache. Stores tokens in a mapping that lasts as long as the object.

Useful for applications like web interfaces.

put(entity, token)

Add or set the token for an entity

Parameters:
  • entity (str) – token’s owner

  • token (str) – token to store

get(entity)

Get the token for an entity

Parameters:

entity (str) – token’s owner

Return type:

str | None

Returns:

token, or None if not in cache

delete(entity)

Remove the token for an entity

Parameters:

entity (str) – token’s owner

Exceptions

class netauth.error.NetAuthException(details, *args)

Base class for exceptions raised by netauth

class netauth.error.NetAuthRpcError(details, code, *args)

Base class for exceptions originating from the NetAuth server

class netauth.error.RequestorUnqualifiedError(details, code, *args)
class netauth.error.MalformedRequestError(details, code, *args)
class netauth.error.InternalError(details, code, *args)
class netauth.error.UnauthenticatedError(details, code, *args)
class netauth.error.ReadOnlyError(details, code, *args)
class netauth.error.ExistsError(details, code, *args)
class netauth.error.DoesNotExistError(details, code, *args)