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 toport (
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 assecret (
str|Callable[[],str] |None) – entity’s secret, or a callback for retrieving the entity’s secrettoken_cache (
TokenCache|None) – aTokenCacheto store tokens in. If not specified, usesMemoryTokenCache.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, orNone(default) to retrieve them from the default location chosen by the gRPC runtime)insecure (
bool) – disable TLS (default:False)
- Raises:
NetAuthException – if
serveris 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:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
ExistsError – if the entity ID or number already exists
InternalError – if some other error occurred during creation
NetAuthRpcError – if a gRPC error occurred
- entity_update(id, meta)
Update the generic metadata on an existing entity.
- Parameters:
id (
str) – the entity’s IDmeta (
EntityMeta) – the new metadata values
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the entity does not exist
InternalError – if some other error occurred during update
NetAuthRpcError – if a gRPC error occurred
- entity_info(id)
Returns information about an entity. Does not require authentication.
- Parameters:
id (
str) – the entity’s ID- Raises:
DoesNotExistError – if the entity does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- Return type:
Entity|None- Returns:
the entity or
Noneif not found
- entity_search(expr)
Searches all entities. Does not require authentication.
- Parameters:
expr (
str) – expression to search for- Raises:
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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 IDaction (
Action) – action to perform (Upsert,Read,ClearFuzzy, orClearExact)key (
str) – key to read from or write to. If'*', operate on all keys.value (
str) – value to write, if writing
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided or an invalid
Actionwas givenUnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the entity does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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 IDkey (
str) – the key to addvalues (
list[str]) – the values to add
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the entity does not exist
ExistsError – if the key already exists
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- entity_kv_get(id, key)
Returns values for the requested key if it exists.
- Parameters:
id (
str) – target entity IDkey (
str) – the key to retrieve. If'*', get all keys.
- Raises:
DoesNotExistError – if the entity or key does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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 IDkey (
str) – the key to delete
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the entity or key does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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 IDkey (
str) – the key to replacevalues (
list[str]) – the values to add
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the entity or key does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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 IDaction (
Action) – action to perform (Add,Drop, orRead)kind (
str) – type of key. If'*', operate on all key types.key (
str) – key value
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided or an invalid
Actionwas givenUnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the entity does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the entity does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the entity does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- entity_unlock(id)
Unsets the lock bit on the target entity.
- Parameters:
id (
str) – target entity ID- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the entity does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- entity_groups(id)
Retrieves the effective group memberships of the target entity.
- Parameters:
id (
str) – target entity ID- Raises:
DoesNotExistError – if the entity does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- Return type:
list[Group]
- auth_entity(id, secret)
Perform authentication for an entity. Does not acquire a token.
- Parameters:
id (
str) – target entity IDsecret (
str) – target entity’s secret
- Raises:
UnauthenticatedError – if authentication failed
NetAuthRpcError – if a gRPC error occurred
- 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 IDsecret (
str) – target entity’s secret
- Raises:
UnauthenticatedError – if authentication failed
InternalError – if an error occurred while issuing a token
NetAuthRpcError – if a gRPC error occurred
- 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:
UnauthenticatedError – if validation failed
NetAuthRpcError – if a gRPC error occurred
- 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 IDsecret (
str) – target entity’s new secretold_secret (
str|None) – target entity’s current secret, if needed
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid or (when changing its own secret) if
old_secretwas not validRequestorUnqualifiedError – if the requestor does not have the necessary capabilities
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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 groupnumber (
int) – the new group’s number. Strongly recommended to be unique. If not provided, the next valid number will be selected and assigned.
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
ExistsError – if the group name or number already exists
InternalError – if some other error occurred during creation
NetAuthRpcError – if a gRPC error occurred
- group_update(group)
Update group information. Fields that cannot be rewritten will be ignored.
- Parameters:
group (
Group) – new group information- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the group does not exist
InternalError – if some other error occurred during update
NetAuthRpcError – if a gRPC error occurred
- group_info(name)
Returns information about a group. Does not require authentication.
- Parameters:
name (
str) – target group’s name- Raises:
DoesNotExistError – if the group does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- Return type:
- 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 nameaction (
Action) – action to perform (Upsert,Read,ClearFuzzy, orClearExact)key (
str) – key to read from or write to. If'*', operate on all keys.value (
str) – value to write, if writing
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided or an invalid
Actionwas givenUnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the group does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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 namekey (
str) – the key to addvalues (
list[str]) – the values to add
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the group does not exist
ExistsError – if the key already exists (NetAuth >0.6.1)
InternalError – if the key already exists (NetAuth <=0.6.1) or some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- group_kv_get(name, key)
Returns values for the requested key if it exists.
- Parameters:
name (
str) – target group namekey (
str) – the key to retrieve. If'*', get all keys.
- Raises:
DoesNotExistError – if the group or key does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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 namekey (
str) – the key to delete
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the group or key does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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 namekey (
str) – the key to replacevalues (
list[str]) – the values to add
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the group or key does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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 nameaction (
RuleAction) – type of rule action to taketarget (
str) – target group name
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the group does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- group_add_member(group, entity)
Add a member to a group.
- Parameters:
group (
str) – target group nameentity (
str) – ID of the entity to add
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- group_del_member(group, entity)
Remove a member from a group.
- Parameters:
group (
str) – target group nameentity (
str) – ID of the entity to remove
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided
UnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
DoesNotExistError – if the group does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- group_members(name)
Returns the membership of a group, include any alterations from rules.
- Parameters:
name (
str) – the name of the group- Raises:
DoesNotExistError – if the group does not exist
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- Return type:
list[Entity]- Returns:
the group members
- group_search(expr)
Searches all groups. Does not require authentication.
- Parameters:
expr (
str) – expression to search for- Raises:
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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 onaction (
Action) – action to perform (AddorDrop)capability (
Capability) – capability to add or dropdirect (
bool) – set the capability on an entitytarget(discouraged, default:False)
- Raises:
ReadOnlyError – if the server is read-only
MalformedRequestError – if a token was not provided or an invalid
Actionwas givenUnauthenticatedError – if the token was not valid
RequestorUnqualifiedError – if the requestor does not have the necessary capabilities
InternalError – if some other error occurred during the request
NetAuthRpcError – if a gRPC error occurred
- 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:
- 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>
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 ownertoken (
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
Noneif 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 ownertoken (
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
Noneif 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 ownertoken (
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
Noneif 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)