Code fix, consistency preference (#1578)

* Code fix, consistency preference

* Code cleanup

* Code cleanup for sso assignments

* Fix typo

* Shorten lines
This commit is contained in:
Ross Scroggs
2022-11-22 04:08:15 -08:00
committed by GitHub
parent 3313295532
commit 9af0a5d843
3 changed files with 133 additions and 92 deletions

View File

@@ -1548,21 +1548,41 @@ gam print group-members|groups-members [todrive]
[roles <GroupRoleList>] [membernames] [fields <MembersFieldNameList>] [roles <GroupRoleList>] [membernames] [fields <MembersFieldNameList>]
[includederivedmembership] [includederivedmembership]
gam create inboundssoprofile name <String> entityid <String> loginurl <URL> logouturl <URL> changepasswordurl <URL> <SSOProfileDisplayName> ::= <String>
gam update inboundssoprofile <String> [entityid <String>] [loginurl <URL>] [logouturl <URL>] [changepasswordurl <URL>] <SSOProfileName> ::= id:inboundSamlSsoProfiles/<String>
gam info inboundssoprofile <String> <SSOProfileItem> ::= <SSOProfileDisplayName>|<SSOProfileName>
gam delete inboundssoprofile <String> <SSOProfileItemList> ::= "<SSOProfileItem>(,<SSOProfileItem>)*"
gam print inboundssoprofiles
gam create inboundssocredentials profile <String> (pemfile <FileName>)|(generatekey [keysize 1024|2048|4096]) [replaceolddest] gam create inboundssoprofile [name <SSOProfileDisplayName>]
gam delete inboundssocredentials <String> [entityid <String>] [loginurl <URL>] [logouturl <URL>] [changepasswordurl <URL>]
gam print inboundssocredentials [profile|profiles <StringList>] gam update inboundssoprofile <SSOProfileItem>
[entityid <String>] [loginurl <URL>] [logouturl <URL>] [changepasswordurl <URL>]
gam delete inboundssoprofile <SSOProfileItem>
gam info inboundssoprofile <SSOProfileItem>
gam show inboundssoprofiles
gam print inboundssoprofiles [todrive]
<SSOCredentialsName> ::= [id:]inboundSamlSsoProfiles/<String>/idpCredentials/<String>
gam create inboundssocredential profile <SSOProfileItem>
(pemfile <FileName>)|(generatekey [keysize 1024|2048|4096]) [replaceolddest]
gam delete inboundssocredential <SSOCredentialsName>
gam show inboundssocredentials [profile|profiles <SSOProfileItemList>]
gam print inboundssocredentials [profile|profiles <SSOProfileItemList>] [todrive]
<SSOAssignmentSelector> ::=
groups/<String> |
group:<EmailAddress> |
orgunits/<String> |
orgunit:<OrgUnitPath>
gam create inboundssoassignment (group <GroupItem> rank <Number>)|(ou|org|orgunit <OrgUnitItem>) gam create inboundssoassignment (group <GroupItem> rank <Number>)|(ou|org|orgunit <OrgUnitItem>)
(mode sso_off)|(mode saml_sso profile <String>)(mode domain_wide_saml_if_enabled) [neverredirect] (mode sso_off)|(mode saml_sso profile <SSOProfileItem>)(mode domain_wide_saml_if_enabled) [neverredirect]
gam update inboundssoassignment [(group <GroupItem> rank <Number>)|(ou|org|orgunit <OrgUnitItem>)] gam update inboundssoassignment [(group <GroupItem> rank <Number>)|(ou|org|orgunit <OrgUnitItem>)]
[(mode sso_off)|(mode saml_sso profile <String>)(mode domain_wide_saml_if_enabled)] [neverredirect] [(mode sso_off)|(mode saml_sso profile <SSOProfileItem>)(mode domain_wide_saml_if_enabled)] [neverredirect]
gam print inboundssoassignments gam info inboundssoassignment <SSOAssignmentSelector>
gam show inboundssoassignments
gam print inboundssoassignments [todrive]
gam send userinvitation <EmailAddress> gam send userinvitation <EmailAddress>
gam cancel userinvitation <EmailAddress> gam cancel userinvitation <EmailAddress>

View File

@@ -9501,7 +9501,7 @@ def doUndeleteUser():
i = 4 i = 4
while i < len(sys.argv): while i < len(sys.argv):
myarg = sys.argv[i].lower() myarg = sys.argv[i].lower()
if myarg in ['ou', 'org']: if myarg in ['ou', 'org', 'orgunit']:
orgUnit = gapi_directory_orgunits.makeOrgUnitPathAbsolute( orgUnit = gapi_directory_orgunits.makeOrgUnitPathAbsolute(
sys.argv[i + 1]) sys.argv[i + 1])
i += 2 i += 2
@@ -11572,14 +11572,14 @@ def ProcessGAMCommand(args):
gapi_cloudidentity_groups.update() gapi_cloudidentity_groups.update()
elif argument in ['nickname', 'alias']: elif argument in ['nickname', 'alias']:
doUpdateAlias() doUpdateAlias()
elif argument in ['inboundssoassignment', 'inboundssoasignments']:
gapi_cloudidentity_inboundsso.update_assignment()
elif argument in ['ou', 'org', 'orgunit']: elif argument in ['ou', 'org', 'orgunit']:
gapi_directory_orgunits.update() gapi_directory_orgunits.update()
elif argument == 'resource': elif argument == 'resource':
gapi_directory_resource.updateResourceCalendar() gapi_directory_resource.updateResourceCalendar()
elif argument in ['inboundssoprofile', 'inboundssoprofiles']: elif argument in ['inboundssoprofile', 'inboundssoprofiles']:
gapi_cloudidentity_inboundsso.update_profile() gapi_cloudidentity_inboundsso.update_profile()
elif argument in ['inboundssoassignment', 'inboundssoasignments']:
gapi_cloudidentity_inboundsso.update_assignment()
elif argument == 'cros': elif argument == 'cros':
gapi_directory_cros.doUpdateCros() gapi_directory_cros.doUpdateCros()
elif argument == 'mobile': elif argument == 'mobile':
@@ -11645,7 +11645,7 @@ def ProcessGAMCommand(args):
gapi_cloudidentity_inboundsso.info_profile() gapi_cloudidentity_inboundsso.info_profile()
elif argument in ['inboundssoassignment', 'inboundssoassignments']: elif argument in ['inboundssoassignment', 'inboundssoassignments']:
gapi_cloudidentity_inboundsso.info_assignment() gapi_cloudidentity_inboundsso.info_assignment()
elif argument in ['org', 'ou', 'orgunit']: elif argument in ['ou', 'org', 'orgunit']:
gapi_directory_orgunits.info() gapi_directory_orgunits.info()
elif argument == 'resource': elif argument == 'resource':
gapi_directory_resource.getResourceCalendarInfo() gapi_directory_resource.getResourceCalendarInfo()
@@ -11718,12 +11718,12 @@ def ProcessGAMCommand(args):
gapi_cloudidentity_devices.delete_user() gapi_cloudidentity_devices.delete_user()
elif argument == 'cigroup': elif argument == 'cigroup':
gapi_cloudidentity_groups.delete() gapi_cloudidentity_groups.delete()
elif argument in ['inboundssoprofile', 'inboundssoprofiles']:
gapi_cloudidentity_inboundsso.delete_profile()
elif argument in ['nickname', 'alias']: elif argument in ['nickname', 'alias']:
doDeleteAlias() doDeleteAlias()
elif argument in ['org', 'ou', 'orgunit']: elif argument in ['ou', 'org', 'orgunit']:
gapi_directory_orgunits.delete() gapi_directory_orgunits.delete()
elif argument in ['inboundssoprofile', 'inboundssoprofiles']:
gapi_cloudidentity_inboundsso.delete_profile()
elif argument in ['inboundssocredential', 'inboundssocredentials']: elif argument in ['inboundssocredential', 'inboundssocredentials']:
gapi_cloudidentity_inboundsso.delete_credentials() gapi_cloudidentity_inboundsso.delete_credentials()
elif argument == 'resource': elif argument == 'resource':
@@ -11815,14 +11815,14 @@ def ProcessGAMCommand(args):
gapi_chromemanagement.printShowCrosTelemetry('print') gapi_chromemanagement.printShowCrosTelemetry('print')
elif argument in ['groupmembers', 'groupsmembers']: elif argument in ['groupmembers', 'groupsmembers']:
gapi_directory_groups.print_members() gapi_directory_groups.print_members()
elif argument in ['inboundssoassignment', 'inboundssoassignments']:
gapi_cloudidentity_inboundsso.print_show_assignments()
elif argument in ['cigroupmembers', 'cigroupsmembers']: elif argument in ['cigroupmembers', 'cigroupsmembers']:
gapi_cloudidentity_groups.print_members() gapi_cloudidentity_groups.print_members()
elif argument in ['inboundssoprofile', 'inboundssoprofiles']: elif argument in ['inboundssoprofile', 'inboundssoprofiles']:
gapi_cloudidentity_inboundsso.print_show_profiles() gapi_cloudidentity_inboundsso.print_show_profiles()
elif argument in ['inboundssocredential', 'inboundssocredentials']: elif argument in ['inboundssocredential', 'inboundssocredentials']:
gapi_cloudidentity_inboundsso.print_show_credentials() gapi_cloudidentity_inboundsso.print_show_credentials()
elif argument in ['inboundssoassignment', 'inboundssoassignments']:
gapi_cloudidentity_inboundsso.print_show_assignments()
elif argument in ['orgs', 'ous']: elif argument in ['orgs', 'ous']:
gapi_directory_orgunits.print_() gapi_directory_orgunits.print_()
elif argument == 'privileges': elif argument == 'privileges':

View File

@@ -76,18 +76,17 @@ def profile_displayname_to_name(displayName, ci=None):
profiles = gapi.get_all_pages(ci.inboundSamlSsoProfiles(), profiles = gapi.get_all_pages(ci.inboundSamlSsoProfiles(),
'list', 'list',
'inboundSamlSsoProfiles', 'inboundSamlSsoProfiles',
filter=_filter, filter=_filter)
)
matches = [] matches = []
for profile in profiles: for profile in profiles:
if displayName.lower() == profile.get('displayName', '').lower(): if displayName.lower() == profile.get('displayName', '').lower():
matches.append(profile) matches.append(profile)
if len(matches) == 1: if len(matches) == 1:
return matches[0]['name'] return matches[0]['name']
elif len(matches) == 0: if len(matches) == 0:
controlflow.system_error_exit(3, f'No Inbound SSO profile matching the name {displayName}') controlflow.system_error_exit(3, f'No Inbound SSO profile matches the name {displayName}')
else: else:
err_text = f'Multiple profiles matching {displayName}:\n\n' err_text = f'Multiple profiles match {displayName}:\n\n'
for m in matches: for m in matches:
err_text += f' {m["name"]} {m["displayName"]}\n' err_text += f' {m["name"]} {m["displayName"]}\n'
controlflow.system_error_exit(3, err_text) controlflow.system_error_exit(3, err_text)
@@ -114,18 +113,18 @@ def assignment_by_target(target, ci=None):
ou_name = target[8:] ou_name = target[8:]
target = get_orgunit_id(ou_name) target = get_orgunit_id(ou_name)
else: else:
controlflow.system_error_exit(3, 'assignments should be prefixed with group: or orgunit:') controlflow.system_error_exit(3, 'assignments should be prefixed with ' +
'group:, groups/, orgunit: or orgunits/')
customer = get_sso_customer() customer = get_sso_customer()
_filter = f'customer=="{customer}"' _filter = f'customer=="{customer}"'
assignments = gapi.get_all_pages(ci.inboundSsoAssignments(), assignments = gapi.get_all_pages(ci.inboundSsoAssignments(),
'list', 'list',
'inboundSsoAssignments', 'inboundSsoAssignments',
filter=_filter, filter=_filter)
)
for assignment in assignments: for assignment in assignments:
if target_type in assignment and assignment[target_type] == target: if target_type in assignment and assignment[target_type] == target:
return assignment return assignment
controlflow.system_error_exit(3, f'No SSO profile assigned to group {target}') controlflow.system_error_exit(3, f'No SSO profile assigned to {target_type} {target}')
'''gam create inboundssoprofile''' '''gam create inboundssoprofile'''
@@ -136,9 +135,14 @@ def create_profile():
'displayName': 'SSO Profile' 'displayName': 'SSO Profile'
} }
body = parse_profile(body, 3) body = parse_profile(body, 3)
result = gapi.call(ci.inboundSamlSsoProfiles(), 'create', body=body) result = gapi.call(ci.inboundSamlSsoProfiles(),
display.print_json(result) 'create',
body=body)
if result.get('done'):
print(f'Created profile {result["response"]["name"]}')
display.print_json(result['response'])
else:
controlflow.system_error_exit(3, 'Create did not finish {result}')
'''gam print inboundssoprofiles''' '''gam print inboundssoprofiles'''
def print_show_profiles(action='print'): def print_show_profiles(action='print'):
@@ -153,13 +157,12 @@ def print_show_profiles(action='print'):
todrive = True todrive = True
i += 1 i += 1
else: else:
controlflow.invalid_argument_exit(myarg, 'gam print inboundssoprofiles') controlflow.invalid_argument_exit(myarg, f'gam {action} inboundssoprofiles')
profiles = gapi.get_all_pages(ci.inboundSamlSsoProfiles(), profiles = gapi.get_all_pages(ci.inboundSamlSsoProfiles(),
'list', 'list',
'inboundSamlSsoProfiles', 'inboundSamlSsoProfiles',
filter=_filter, filter=_filter)
)
if action == 'show': if action == 'show':
for profile in profiles: for profile in profiles:
display.print_json(profile) display.print_json(profile)
@@ -203,8 +206,7 @@ def info_profile(return_only=False, displayName=None, ci=None):
name = profile_displayname_to_name(displayName, ci) name = profile_displayname_to_name(displayName, ci)
result = gapi.call(ci.inboundSamlSsoProfiles(), result = gapi.call(ci.inboundSamlSsoProfiles(),
'get', 'get',
name=name, name=name)
)
if return_only: if return_only:
return result return result
display.print_json(result) display.print_json(result)
@@ -217,7 +219,7 @@ def delete_profile():
'delete', 'delete',
name=name) name=name)
if result.get('done'): if result.get('done'):
print(f' deleted profile {name}.') print(f'Deleted profile {name}.')
else: else:
controlflow.system_error_exit(3, 'Delete did not finish: {result}') controlflow.system_error_exit(3, 'Delete did not finish: {result}')
@@ -256,11 +258,9 @@ def create_credentials():
key_size) key_size)
i += 2 i += 2
else: else:
controlflow.invalid_argument_exit(myarg, controlflow.invalid_argument_exit(myarg, 'gam create inboundssocredential')
'gam create inboundssocredential')
if not parent: if not parent:
controlflow.missing_argument_exit('profile', controlflow.missing_argument_exit('profile', 'gam create inboundssocredential')
'gam create inboundssocredential')
if replace_oldest: if replace_oldest:
fields='nextPageToken,idpCredentials(name,updateTime)' fields='nextPageToken,idpCredentials(name,updateTime)'
current_creds = gapi.get_all_pages( current_creds = gapi.get_all_pages(
@@ -296,13 +296,12 @@ def create_credentials():
result = gapi.call(ci.inboundSamlSsoProfiles().idpCredentials(), result = gapi.call(ci.inboundSamlSsoProfiles().idpCredentials(),
'add', 'add',
parent=parent, parent=parent,
fields='done,response',
body=body) body=body)
if result.get('done'): if result.get('done'):
print(f'Created credential {result["response"]["name"]}') print(f'Created credential {result["response"]["name"]}')
display.print_json(result['response'])
else: else:
controlflow.system_error_exit(3, controlflow.system_error_exit(3, 'Create did not finish {result}')
'Create did not finish {result}')
'''gam delete inboundssocredential''' '''gam delete inboundssocredential'''
@@ -315,7 +314,7 @@ def delete_credentials(ci=None, name=None):
'delete', 'delete',
name=name) name=name)
if result.get('done'): if result.get('done'):
print(f' deleted credential {name}') print(f'Deleted credential {name}')
else: else:
controlflow.system_error_exit(3, 'Delete did not finish {result}') controlflow.system_error_exit(3, 'Delete did not finish {result}')
@@ -329,16 +328,14 @@ def print_show_credentials(action='print'):
while i < len(sys.argv): while i < len(sys.argv):
myarg = sys.argv[i].lower().replace('_', '') myarg = sys.argv[i].lower().replace('_', '')
if myarg in ['profile', 'profiles']: if myarg in ['profile', 'profiles']:
profiles = sys.argv[i+1].split(',') profiles = [profile_displayname_to_name(profile, ci)
for profile in profiles: for profile in sys.argv[i+1].split(',')]
profile = profile_displayname_to_name(profile, ci) i += 2
elif myarg == 'todrive': elif myarg == 'todrive':
todrive = True todrive = True
i += 1 i += 1
for profile in sys.argv[i+1].replace(',', ' ').split():
profiles.append(profile_displayname_to_name(profile, ci))
else: else:
controlflow.invalid_argument_exit(myarg, 'gam print inboundssocredentials') controlflow.invalid_argument_exit(myarg, f'gam {action} inboundssocredentials')
if not profiles: if not profiles:
customer = get_sso_customer() customer = get_sso_customer()
_filter = f'customer=="{customer}"' _filter = f'customer=="{customer}"'
@@ -346,8 +343,7 @@ def print_show_credentials(action='print'):
'list', 'list',
'inboundSamlSsoProfiles', 'inboundSamlSsoProfiles',
fields='inboundSamlSsoProfiles/name', fields='inboundSamlSsoProfiles/name',
filter=_filter, filter=_filter)
)
profiles = [p['name'] for p in profiles] profiles = [p['name'] for p in profiles]
if action == 'print': if action == 'print':
titles = [] titles = []
@@ -383,7 +379,8 @@ def parse_assignment(body, i, ci):
body['rank'] = int(sys.argv[i+1]) body['rank'] = int(sys.argv[i+1])
i += 2 i += 2
elif myarg == 'mode': elif myarg == 'mode':
mode_choices = gapi.get_enum_values_minus_unspecified( mode_choices = \
gapi.get_enum_values_minus_unspecified(
ci._rootDesc['schemas']['InboundSsoAssignment']['properties']['ssoMode']['enum']) ci._rootDesc['schemas']['InboundSsoAssignment']['properties']['ssoMode']['enum'])
body['ssoMode'] = sys.argv[i+1].upper() body['ssoMode'] = sys.argv[i+1].upper()
if body['ssoMode'] not in mode_choices: if body['ssoMode'] not in mode_choices:
@@ -418,9 +415,21 @@ def parse_assignment(body, i, ci):
return body return body
def update_assignment_target_names(assignment, ci, cd):
if 'targetGroup' in assignment:
assignment['targetGroupEmail'] = \
gapi_cloudidentity_groups.group_id_to_email(ci,
assignment['targetGroup'])
elif 'targetOrgUnit' in assignment:
ou_id = assignment['targetOrgUnit'].split('/')[1]
assignment['targetOrgUnitPath'] = \
gapi_directory_orgunits.orgunit_from_orgunitid(f'id:{ou_id}', cd)
'''gam create inboundssoassignment''' '''gam create inboundssoassignment'''
def create_assignment(): def create_assignment():
ci = build() ci = build()
cd = gapi_directory.build()
body = { body = {
'customer': get_sso_customer(), 'customer': get_sso_customer(),
} }
@@ -428,40 +437,59 @@ def create_assignment():
result = gapi.call(ci.inboundSsoAssignments(), result = gapi.call(ci.inboundSsoAssignments(),
'create', 'create',
body=body) body=body)
display.print_json(result) if result.get('done'):
print(f'Created assignment {result["response"]["name"]}')
update_assignment_target_names(result['response'], ci, cd)
display.print_json(result['response'])
else:
controlflow.system_error_exit(3, 'Create did not finish {result}')
def get_assignment_name(name):
if name.startswith('id:') or name.startswith('uid:'):
name = name.split(':', 1)[1]
if not name.startswith('inboundSsoAssignments/'):
name = f'inboundSsoAssignments/{name}'
return name
'''gam update inboundssoassignment''' '''gam update inboundssoassignment'''
def update_assignment(): def update_assignment():
ci = build() ci = build()
name = assignment_target_to_name(sys.argv[3], ci) cd = gapi_directory.build()
body = {} name = get_assignment_name(sys.argv[3])
body = parse_assignment(body, 4, ci) body = parse_assignment({}, 4, ci)
updateMask = ','.join(list(body.keys())) updateMask = ','.join(list(body.keys()))
result = gapi.call(ci.inboundSsoAssignments(), result = gapi.call(ci.inboundSsoAssignments(),
'patch', 'patch',
name=name, name=name,
updateMask=updateMask, updateMask=updateMask,
body=body, body=body)
) if result.get('done'):
display.print_json(result) print(f'Updated assignment {result["response"]["name"]}')
update_assignment_target_names(result['response'], ci, cd)
display.print_json(result['response'])
else:
controlflow.system_error_exit(3, 'Update did not finish {result}')
'''gam info inboundssoassignment''' '''gam info inboundssoassignment'''
def info_assignment(): def info_assignment():
ci = build() ci = build()
cd = gapi_directory.build()
assignment = assignment_by_target(sys.argv[3], ci) assignment = assignment_by_target(sys.argv[3], ci)
update_assignment_target_names(assignment, ci, cd)
profile = assignment.get('samlSsoInfo', {}).get('inboundSamlSsoProfile') profile = assignment.get('samlSsoInfo', {}).get('inboundSamlSsoProfile')
if profile: if profile:
assignment['samlSsoInfo']['inboundSamlSsoProfile'] = info_profile(return_only=True, assignment['samlSsoInfo']['inboundSamlSsoProfile'] = \
displayName=f'id:{profile}', info_profile(return_only=True, displayName=f'id:{profile}', ci=ci)
ci=ci)
display.print_json(assignment) display.print_json(assignment)
'''gam print inboundssoassignments''' '''gam print inboundssoassignments'''
def print_show_assignments(action='print'): def print_show_assignments(action='print'):
ci = build() ci = build()
cd = gapi_directory.build()
customer = get_sso_customer() customer = get_sso_customer()
_filter = f'customer=="{customer}"' _filter = f'customer=="{customer}"'
todrive = False todrive = False
@@ -472,29 +500,22 @@ def print_show_assignments(action='print'):
todrive = True todrive = True
i += 1 i += 1
else: else:
controlflow.invalid_argument_exit(myarg, 'gam print inboundssoassignments') controlflow.invalid_argument_exit(myarg,
f'gam {action} inboundssoassignments')
assignments = gapi.get_all_pages(ci.inboundSsoAssignments(), assignments = gapi.get_all_pages(ci.inboundSsoAssignments(),
'list', 'list',
'inboundSsoAssignments', 'inboundSsoAssignments',
filter=_filter, filter=_filter)
)
cd = gapi_directory.build()
for assignment in assignments:
if 'targetGroup' in assignment:
assignment['groupEmail'] = gapi_cloudidentity_groups.group_id_to_email(ci, assignment['targetGroup'])
if 'targetOrgUnit' in assignment:
ou_id = assignment['targetOrgUnit']
ou_id = ou_id.split('/')[1]
ou_id = f'id:{ou_id}'
assignment['orgUnit'] = gapi_directory_orgunits.orgunit_from_orgunitid(ou_id, cd)
if action == 'show': if action == 'show':
for assignment in assignments: for assignment in assignments:
update_assignment_target_names(assignment, ci, cd)
display.print_json(assignment) display.print_json(assignment)
print() print()
elif action == 'print': elif action == 'print':
titles = [] titles = []
csv_rows = [] csv_rows = []
for assignment in assignments: for assignment in assignments:
update_assignment_target_names(assignment, ci, cd)
csv_row = utils.flatten_json(assignment) csv_row = utils.flatten_json(assignment)
for item in csv_row: for item in csv_row:
if item not in titles: if item not in titles: