@@ -27,20 +27,25 @@ def parse_args():
27
27
'--no-validate' , '-n' , action = 'store_true' ,
28
28
help = 'Directory path to search recursively' ,
29
29
)
30
+ parser .add_argument (
31
+ '--file-pattern' , '-p' , default = PROJECT_JSON_PATTERN ,
32
+ help = 'Pattern to match JSON file names against' ,
33
+ )
30
34
return parser .parse_args ()
31
35
32
36
33
37
# For requirements on GCP project IDs, see
34
38
# https://cloud.google.com/resource-manager/docs/creating-managing-projects
35
39
PROJECT_PATTERN = r"[a-z][a-z0-9\-]{4,28}[a-z0-9]"
36
- FILE_PATTERN = re . compile ( PROJECT_PATTERN + r"-[0-9a-f]{12}\.json" )
40
+ PROJECT_JSON_PATTERN = PROJECT_PATTERN + r"-[0-9a-f]{12}\.json"
37
41
38
42
39
- def find_key_paths (dir_path : str ):
40
- """ Finds files whose name matches the JSON SA key pattern """
43
+ def find_key_paths (dir_path : str , file_pattern : str ):
44
+ """ Finds files whose name matches `file_pattern` """
45
+ file_re = re .compile (file_pattern )
41
46
for dirpath , _ , files in os .walk (dir_path ):
42
47
for file in files :
43
- if FILE_PATTERN .match (file ):
48
+ if file_re .match (file ):
44
49
yield os .path .join (dirpath , file )
45
50
46
51
@@ -52,13 +57,13 @@ def is_valid_key(file_path: str):
52
57
)
53
58
credentials .refresh (google .auth .transport .requests .Request ())
54
59
return True
55
- except (ValueError , google .auth .exceptions .RefreshError ):
60
+ except (AttributeError , ValueError , google .auth .exceptions .RefreshError ):
56
61
return False
57
62
58
63
59
- def find_valid_keys (dir_path : str ):
64
+ def find_valid_keys (dir_path : str , file_pattern : str ):
60
65
""" Recursively walks `dir_path` and finds valid GCP SA keys """
61
- for path in find_key_paths (dir_path ):
66
+ for path in find_key_paths (dir_path , file_pattern ):
62
67
if is_valid_key (path ):
63
68
yield path
64
69
@@ -68,12 +73,12 @@ def main():
68
73
args = parse_args ()
69
74
70
75
if args .no_validate :
71
- for path in find_key_paths (args .dir_path ):
76
+ for path in find_key_paths (args .dir_path , args . file_pattern ):
72
77
print (path )
73
78
sys .exit (0 )
74
79
75
80
found = False
76
- for path in find_valid_keys (args .dir_path ):
81
+ for path in find_valid_keys (args .dir_path , args . file_pattern ):
77
82
print (path , file = sys .stderr )
78
83
found = True
79
84
0 commit comments